OpenTTD: src/autoreplace_cmd.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

autoreplace_cmd.cpp
Go to the documentation of this file.
1 /* $Id: autoreplace_cmd.cpp 26482 2014-04-23 20:13:33Z rubidium $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "train.h"
15 #include "command_func.h"
16 #include "engine_func.h"
17 #include "vehicle_func.h"
18 #include "autoreplace_func.h"
19 #include "autoreplace_gui.h"
20 #include "articulated_vehicles.h"
21 #include "core/random_func.hpp"
22
23 #include "table/strings.h"
24
25 #include "safeguards.h"
26
27 extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
28 extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
29 extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
30
38 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
39 {
40 uint32 available_cargoes_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
41 uint32 available_cargoes_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
42 return (available_cargoes_a == 0 || available_cargoes_b == 0 || (available_cargoes_a & available_cargoes_b) != 0);
43 }
44
52 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
53 {
54 assert(Engine::IsValidID(from) && Engine::IsValidID(to));
55
56 /* we can't replace an engine into itself (that would be autorenew) */
57 if (from == to) return false;
58
59 const Engine *e_from = Engine::Get(from);
60 const Engine *e_to = Engine::Get(to);
61 VehicleType type = e_from->type;
62
63 /* check that the new vehicle type is available to the company and its type is the same as the original one */
64 if (!IsEngineBuildable(to, type, company)) return false;
65
66 switch (type) {
67 case VEH_TRAIN: {
68 /* make sure the railtypes are compatible */
69 if ((GetRailTypeInfo(e_from->u.rail.railtype)->compatible_railtypes & GetRailTypeInfo(e_to->u.rail.railtype)->compatible_railtypes) == 0) return false;
70
71 /* make sure we do not replace wagons with engines or vice versa */
72 if ((e_from->u.rail.railveh_type == RAILVEH_WAGON) != (e_to->u.rail.railveh_type == RAILVEH_WAGON)) return false;
73 break;
74 }
75
76 case VEH_ROAD:
77 /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
78 if (HasBit(e_from->info.misc_flags, EF_ROAD_TRAM) != HasBit(e_to->info.misc_flags, EF_ROAD_TRAM)) return false;
79 break;
80
81 case VEH_AIRCRAFT:
82 /* make sure that we do not replace a plane with a helicopter or vice versa */
83 if ((e_from->u.air.subtype & AIR_CTOL) != (e_to->u.air.subtype & AIR_CTOL)) return false;
84 break;
85
86 default: break;
87 }
88
89 /* the engines needs to be able to carry the same cargo */
90 return EnginesHaveCargoInCommon(from, to);
91 }
92
99 void CheckCargoCapacity(Vehicle *v)
100 {
101 assert(v == NULL || v->First() == v);
102
103 for (Vehicle *src = v; src != NULL; src = src->Next()) {
104 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
105
106 /* Do we need to more cargo away? */
107 if (src->cargo.TotalCount() <= src->cargo_cap) continue;
108
109 /* We need to move a particular amount. Try that on the other vehicles. */
110 uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
111 for (Vehicle *dest = v; dest != NULL && to_spread != 0; dest = dest->Next()) {
112 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
113 if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
114
115 uint amount = min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
116 src->cargo.Shift(amount, &dest->cargo);
117 to_spread -= amount;
118 }
119
120 /* Any left-overs will be thrown away, but not their feeder share. */
121 if (src->cargo_cap < src->cargo.TotalCount()) src->cargo.Truncate(src->cargo.TotalCount() - src->cargo_cap);
122 }
123 }
124
134 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
135 {
136 assert(!part_of_chain || new_head->IsPrimaryVehicle());
137 /* Loop through source parts */
138 for (Vehicle *src = old_veh; src != NULL; src = src->Next()) {
139 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
140 if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
141 /* Skip vehicles, which do not belong to old_veh */
142 src = src->GetLastEnginePart();
143 continue;
144 }
145 if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
146
147 /* Find free space in the new chain */
148 for (Vehicle *dest = new_head; dest != NULL && src->cargo.TotalCount() > 0; dest = dest->Next()) {
149 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
150 if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
151 /* Skip vehicles, which do not belong to new_head */
152 dest = dest->GetLastEnginePart();
153 continue;
154 }
155 if (dest->cargo_type != src->cargo_type) continue;
156
157 uint amount = min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
158 if (amount <= 0) continue;
159
160 src->cargo.Shift(amount, &dest->cargo);
161 }
162 }
163
164 /* Update train weight etc., the old vehicle will be sold anyway */
165 if (part_of_chain && new_head->type == VEH_TRAIN) Train::From(new_head)->ConsistChanged(CCF_LOADUNLOAD);
166 }
167
174 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
175 {
176
177 uint32 union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
178 uint32 union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
179
180 const Order *o;
181 const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
182 FOR_VEHICLE_ORDERS(u, o) {
183 if (!o->IsRefit() || o->IsAutoRefit()) continue;
184 CargoID cargo_type = o->GetRefitCargo();
185
186 if (!HasBit(union_refit_mask_a, cargo_type)) continue;
187 if (!HasBit(union_refit_mask_b, cargo_type)) return false;
188 }
189
190 return true;
191 }
192
202 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
203 {
204 uint32 available_cargo_types, union_mask;
205 GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
206
207 if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
208
209 CargoID cargo_type;
210 if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
211
212 if (cargo_type == CT_INVALID) {
213 if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
214
215 if (!part_of_chain) return CT_NO_REFIT;
216
217 /* the old engine didn't have cargo capacity, but the new one does
218 * now we will figure out what cargo the train is carrying and refit to fit this */
219
220 for (v = v->First(); v != NULL; v = v->Next()) {
221 if (!v->GetEngine()->CanCarryCargo()) continue;
222 /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
223 if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
224 }
225
226 return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
227 } else {
228 if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
229
230 if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
231
232 return cargo_type;
233 }
234 }
235
244 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
245 {
246 assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
247
248 e = INVALID_ENGINE;
249
250 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
251 /* we build the rear ends of multiheaded trains with the front ones */
252 return CommandCost();
253 }
254
255 bool replace_when_old;
256 e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
257 if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE;
258
259 /* Autoreplace, if engine is available */
260 if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
261 return CommandCost();
262 }
263
264 /* Autorenew if needed */
265 if (v->NeedsAutorenewing(c)) e = v->engine_type;
266
267 /* Nothing to do or all is fine? */
268 if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
269
270 /* The engine we need is not available. Report error to user */
271 return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
272 }
273
282 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
283 {
284 *new_vehicle = NULL;
285
286 /* Shall the vehicle be replaced? */
287 const Company *c = Company::Get(_current_company);
288 EngineID e;
289 CommandCost cost = GetNewEngineType(old_veh, c, true, e);
290 if (cost.Failed()) return cost;
291 if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
292
293 /* Does it need to be refitted */
294 CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
295 if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargoes
296
297 /* Build the new vehicle */
298 cost = DoCommand(old_veh->tile, e, 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
299 if (cost.Failed()) return cost;
300
301 Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
302 *new_vehicle = new_veh;
303
304 /* Refit the vehicle if needed */
305 if (refit_cargo != CT_NO_REFIT) {
306 byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
307
308 cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
309 assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
310 }
311
312 /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
313 if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
314 DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
315 }
316
317 return cost;
318 }
319
326 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
327 {
328 return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
329 }
330
339 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
340 {
341 return DoCommand(0, v->index | (whole_chain ? 1 : 0) << 20, after != NULL ? after->index : INVALID_VEHICLE, flags | DC_NO_CARGO_CAP_CHECK, CMD_MOVE_RAIL_VEHICLE);
342 }
343
350 static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
351 {
352 CommandCost cost = CommandCost();
353
354 /* Share orders */
355 if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, new_head->index | CO_SHARE << 30, old_head->index, DC_EXEC, CMD_CLONE_ORDER));
356
357 /* Copy group membership */
358 if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
359
360 /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
361 if (cost.Succeeded()) {
362 /* Start the vehicle, might be denied by certain things */
363 assert((new_head->vehstatus & VS_STOPPED) != 0);
364 cost.AddCost(CmdStartStopVehicle(new_head, true));
365
366 /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
367 if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
368 }
369
370 /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
371 if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
372 /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
373 new_head->CopyVehicleConfigAndStatistics(old_head);
374
375 /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
376 ChangeVehicleViewports(old_head->index, new_head->index);
377 ChangeVehicleViewWindow(old_head->index, new_head->index);
378 ChangeVehicleNews(old_head->index, new_head->index);
379 }
380
381 return cost;
382 }
383
391 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
392 {
393 Train *old_v = Train::From(*single_unit);
394 assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
395
396 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
397
398 /* Build and refit replacement vehicle */
399 Vehicle *new_v = NULL;
400 cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
401
402 /* Was a new vehicle constructed? */
403 if (cost.Succeeded() && new_v != NULL) {
404 *nothing_to_do = false;
405
406 if ((flags & DC_EXEC) != 0) {
407 /* Move the new vehicle behind the old */
408 CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
409
410 /* Take over cargo
411 * Note: We do only transfer cargo from the old to the new vehicle.
412 * I.e. we do not transfer remaining cargo to other vehicles.
413 * Else you would also need to consider moving cargo to other free chains,
414 * or doing the same in ReplaceChain(), which would be quite troublesome.
415 */
416 TransferCargo(old_v, new_v, false);
417
418 *single_unit = new_v;
419 }
420
421 /* Sell the old vehicle */
422 cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
423
424 /* If we are not in DC_EXEC undo everything */
425 if ((flags & DC_EXEC) == 0) {
426 DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
427 }
428 }
429
430 return cost;
431 }
432
441 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
442 {
443 Vehicle *old_head = *chain;
444 assert(old_head->IsPrimaryVehicle());
445
446 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
447
448 if (old_head->type == VEH_TRAIN) {
449 /* Store the length of the old vehicle chain, rounded up to whole tiles */
450 uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
451
452 int num_units = 0;
453 for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;
454
455 Train **old_vehs = CallocT<Train *>(num_units);
456 Train **new_vehs = CallocT<Train *>(num_units);
457 Money *new_costs = MallocT<Money>(num_units);
458
459 /* Collect vehicles and build replacements
460 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
461 int i;
462 Train *w;
463 for (w = Train::From(old_head), i = 0; w != NULL; w = w->GetNextUnit(), i++) {
464 assert(i < num_units);
465 old_vehs[i] = w;
466
467 CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
468 cost.AddCost(ret);
469 if (cost.Failed()) break;
470
471 new_costs[i] = ret.GetCost();
472 if (new_vehs[i] != NULL) *nothing_to_do = false;
473 }
474 Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
475
476 /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
477 if (cost.Succeeded()) {
478 /* Separate the head, so we can start constructing the new chain */
479 Train *second = Train::From(old_head)->GetNextUnit();
480 if (second != NULL) cost.AddCost(CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
481
482 assert(Train::From(new_head)->GetNextUnit() == NULL);
483
484 /* Append engines to the new chain
485 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
486 * That way we also have less trouble when exceeding the unitnumber limit.
487 * OTOH the vehicle attach callback is more expensive this way :s */
488 Train *last_engine = NULL;
489 if (cost.Succeeded()) {
490 for (int i = num_units - 1; i > 0; i--) {
491 Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
492
493 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
494
495 if (new_vehs[i] != NULL) {
496 /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
497 * moving the wagon in front may fail later due to unitnumber limit.
498 * (We have to attach wagons without DC_AUTOREPLACE.) */
499 CmdMoveVehicle(old_vehs[i], NULL, DC_EXEC | DC_AUTOREPLACE, false);
500 }
501
502 if (last_engine == NULL) last_engine = append;
503 cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
504 if (cost.Failed()) break;
505 }
506 if (last_engine == NULL) last_engine = new_head;
507 }
508
509 /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
510 if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
511
512 /* Append/insert wagons into the new vehicle chain
513 * 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.
514 */
515 if (cost.Succeeded()) {
516 for (int i = num_units - 1; i > 0; i--) {
517 assert(last_engine != NULL);
518 Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
519
520 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
521 /* Insert wagon after 'last_engine' */
522 CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
523
524 /* When we allow removal of wagons, either the move failing due
525 * to the train becoming too long, or the train becoming longer
526 * would move the vehicle to the empty vehicle chain. */
527 if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
528 CmdMoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
529 break;
530 }
531
532 cost.AddCost(res);
533 if (cost.Failed()) break;
534 } else {
535 /* We have reached 'last_engine', continue with the next engine towards the front */
536 assert(append == last_engine);
537 last_engine = last_engine->GetPrevUnit();
538 }
539 }
540 }
541
542 /* Sell superfluous new vehicles that could not be inserted. */
543 if (cost.Succeeded() && wagon_removal) {
544 assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
545 for (int i = 1; i < num_units; i++) {
546 Vehicle *wagon = new_vehs[i];
547 if (wagon == NULL) continue;
548 if (wagon->First() == new_head) break;
549
550 assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
551
552 /* Sell wagon */
553 CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
554 assert(ret.Succeeded());
555 new_vehs[i] = NULL;
556
557 /* Revert the money subtraction when the vehicle was built.
558 * This value is different from the sell value, esp. because of refitting */
559 cost.AddCost(-new_costs[i]);
560 }
561 }
562
563 /* The new vehicle chain is constructed, now take over orders and everything... */
564 if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
565
566 if (cost.Succeeded()) {
567 /* Success ! */
568 if ((flags & DC_EXEC) != 0 && new_head != old_head) {
569 *chain = new_head;
570 }
571
572 /* Transfer cargo of old vehicles and sell them */
573 for (int i = 0; i < num_units; i++) {
574 Vehicle *w = old_vehs[i];
575 /* Is the vehicle again part of the new chain?
576 * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
577 if (w->First() == new_head) continue;
578
579 if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
580
581 /* Sell the vehicle.
582 * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
583 * it from failing due to engine limits. */
584 cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
585 if ((flags & DC_EXEC) != 0) {
586 old_vehs[i] = NULL;
587 if (i == 0) old_head = NULL;
588 }
589 }
590
591 if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
592 }
593
594 /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
595 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
596 * Note: The vehicle attach callback is disabled here :) */
597 if ((flags & DC_EXEC) == 0) {
598 /* Separate the head, so we can reattach the old vehicles */
599 Train *second = Train::From(old_head)->GetNextUnit();
600 if (second != NULL) CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);
601
602 assert(Train::From(old_head)->GetNextUnit() == NULL);
603
604 for (int i = num_units - 1; i > 0; i--) {
605 CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
606 assert(ret.Succeeded());
607 }
608 }
609 }
610
611 /* Finally undo buying of new vehicles */
612 if ((flags & DC_EXEC) == 0) {
613 for (int i = num_units - 1; i >= 0; i--) {
614 if (new_vehs[i] != NULL) {
615 DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
616 new_vehs[i] = NULL;
617 }
618 }
619 }
620
621 free(old_vehs);
622 free(new_vehs);
623 free(new_costs);
624 } else {
625 /* Build and refit replacement vehicle */
626 Vehicle *new_head = NULL;
627 cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
628
629 /* Was a new vehicle constructed? */
630 if (cost.Succeeded() && new_head != NULL) {
631 *nothing_to_do = false;
632
633 /* The new vehicle is constructed, now take over orders and everything... */
634 cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
635
636 if (cost.Succeeded()) {
637 /* The new vehicle is constructed, now take over cargo */
638 if ((flags & DC_EXEC) != 0) {
639 TransferCargo(old_head, new_head, true);
640 *chain = new_head;
641 }
642
643 /* Sell the old vehicle */
644 cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
645 }
646
647 /* If we are not in DC_EXEC undo everything */
648 if ((flags & DC_EXEC) == 0) {
649 DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
650 }
651 }
652 }
653
654 return cost;
655 }
656
667 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
668 {
669 Vehicle *v = Vehicle::GetIfValid(p1);
670 if (v == NULL) return CMD_ERROR;
671
672 CommandCost ret = CheckOwnership(v->owner);
673 if (ret.Failed()) return ret;
674
675 if (!v->IsChainInDepot()) return CMD_ERROR;
676 if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
677
678 bool free_wagon = false;
679 if (v->type == VEH_TRAIN) {
680 Train *t = Train::From(v);
681 if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
682 free_wagon = !t->IsFrontEngine();
683 if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
684 } else {
685 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
686 }
687
688 const Company *c = Company::Get(_current_company);
689 bool wagon_removal = c->settings.renew_keep_length;
690
691 /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
692 Vehicle *w = v;
693 bool any_replacements = false;
694 while (w != NULL) {
695 EngineID e;
696 CommandCost cost = GetNewEngineType(w, c, false, e);
697 if (cost.Failed()) return cost;
698 any_replacements |= (e != INVALID_ENGINE);
699 w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : NULL);
700 }
701
702 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
703 bool nothing_to_do = true;
704
705 if (any_replacements) {
706 bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
707
708 /* Stop the vehicle */
709 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
710 if (cost.Failed()) return cost;
711
712 assert(free_wagon || v->IsStoppedInDepot());
713
714 /* We have to construct the new vehicle chain to test whether it is valid.
715 * Vehicle construction needs random bits, so we have to save the random seeds
716 * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
717 SavedRandomSeeds saved_seeds;
718 SaveRandomSeeds(&saved_seeds);
719 if (free_wagon) {
720 cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
721 } else {
722 cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
723 }
724 RestoreRandomSeeds(saved_seeds);
725
726 if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
727 CommandCost ret;
728 if (free_wagon) {
729 ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
730 } else {
731 ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
732 }
733 assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
734 }
735
736 /* Restart the vehicle */
737 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
738 }
739
740 if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
741 return cost;
742 }
743
757 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
758 {
759 Company *c = Company::GetIfValid(_current_company);
760 if (c == NULL) return CMD_ERROR;
761
762 EngineID old_engine_type = GB(p2, 0, 16);
763 EngineID new_engine_type = GB(p2, 16, 16);
764 GroupID id_g = GB(p1, 16, 16);
765 CommandCost cost;
766
767 if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
768 if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
769
770 if (new_engine_type != INVALID_ENGINE) {
771 if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
772 if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
773
774 cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, HasBit(p1, 0), flags);
775 } else {
776 cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
777 }
778
779 if (flags & DC_EXEC) {
780 GroupStatistics::UpdateAutoreplace(_current_company);
781 if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
782 }
783 if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
784
785 return cost;
786 }
787