OpenTTD Source  13.0-beta1
vehicle_cmd.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #include "stdafx.h"
11 #include "roadveh.h"
12 #include "news_func.h"
13 #include "airport.h"
14 #include "command_func.h"
15 #include "company_func.h"
16 #include "train.h"
17 #include "aircraft.h"
18 #include "newgrf_text.h"
19 #include "vehicle_func.h"
20 #include "string_func.h"
21 #include "depot_map.h"
22 #include "vehiclelist.h"
23 #include "engine_func.h"
24 #include "articulated_vehicles.h"
25 #include "autoreplace_gui.h"
26 #include "group.h"
27 #include "order_backup.h"
28 #include "ship.h"
29 #include "newgrf.h"
30 #include "company_base.h"
31 #include "core/random_func.hpp"
32 #include "vehicle_cmd.h"
33 #include "aircraft_cmd.h"
34 #include "autoreplace_cmd.h"
35 #include "group_cmd.h"
36 #include "order_cmd.h"
37 #include "roadveh_cmd.h"
38 #include "train_cmd.h"
39 #include "ship_cmd.h"
40 #include <sstream>
41 #include <iomanip>
42 
43 #include "table/strings.h"
44 
45 #include "safeguards.h"
46 
47 /* Tables used in vehicle_func.h to find the right error message for a certain vehicle type */
48 const StringID _veh_build_msg_table[] = {
49  STR_ERROR_CAN_T_BUY_TRAIN,
50  STR_ERROR_CAN_T_BUY_ROAD_VEHICLE,
51  STR_ERROR_CAN_T_BUY_SHIP,
52  STR_ERROR_CAN_T_BUY_AIRCRAFT,
53 };
54 
55 const StringID _veh_sell_msg_table[] = {
56  STR_ERROR_CAN_T_SELL_TRAIN,
57  STR_ERROR_CAN_T_SELL_ROAD_VEHICLE,
58  STR_ERROR_CAN_T_SELL_SHIP,
59  STR_ERROR_CAN_T_SELL_AIRCRAFT,
60 };
61 
62 const StringID _veh_refit_msg_table[] = {
63  STR_ERROR_CAN_T_REFIT_TRAIN,
64  STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE,
65  STR_ERROR_CAN_T_REFIT_SHIP,
66  STR_ERROR_CAN_T_REFIT_AIRCRAFT,
67 };
68 
69 const StringID _send_to_depot_msg_table[] = {
70  STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT,
71  STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT,
72  STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT,
73  STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR,
74 };
75 
76 
87 std::tuple<CommandCost, VehicleID, uint, uint16> CmdBuildVehicle(DoCommandFlag flags, TileIndex tile, EngineID eid, bool use_free_vehicles, CargoID cargo, ClientID client_id)
88 {
89  /* Elementary check for valid location. */
90  if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return { CMD_ERROR, INVALID_VEHICLE, 0, 0 };
91 
92  VehicleType type = GetDepotVehicleType(tile);
93 
94  /* Validate the engine type. */
95  if (!IsEngineBuildable(eid, type, _current_company)) return { CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type), INVALID_VEHICLE, 0, 0 };
96 
97  /* Validate the cargo type. */
98  if (cargo >= NUM_CARGO && cargo != CT_INVALID) return { CMD_ERROR, INVALID_VEHICLE, 0, 0 };
99 
100  const Engine *e = Engine::Get(eid);
102 
103  /* Engines without valid cargo should not be available */
104  CargoID default_cargo = e->GetDefaultCargoType();
105  if (default_cargo == CT_INVALID) return { CMD_ERROR, INVALID_VEHICLE, 0, 0 };
106 
107  bool refitting = cargo != CT_INVALID && cargo != default_cargo;
108 
109  /* Check whether the number of vehicles we need to build can be built according to pool space. */
110  uint num_vehicles;
111  switch (type) {
112  case VEH_TRAIN: num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
113  case VEH_ROAD: num_vehicles = 1 + CountArticulatedParts(eid, false); break;
114  case VEH_SHIP: num_vehicles = 1; break;
115  case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
116  default: NOT_REACHED(); // Safe due to IsDepotTile()
117  }
118  if (!Vehicle::CanAllocateItem(num_vehicles)) return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE, 0, 0 };
119 
120  /* Check whether we can allocate a unit number. Autoreplace does not allocate
121  * an unit number as it will (always) reuse the one of the replaced vehicle
122  * and (train) wagons don't have an unit number in any scenario. */
123  UnitID unit_num = (flags & DC_QUERY_COST || flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
124  if (unit_num == UINT16_MAX) return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE, 0, 0 };
125 
126  /* If we are refitting we need to temporarily purchase the vehicle to be able to
127  * test it. */
128  DoCommandFlag subflags = flags;
129  if (refitting && !(flags & DC_EXEC)) subflags |= DC_EXEC | DC_AUTOREPLACE;
130 
131  /* Vehicle construction needs random bits, so we have to save the random
132  * seeds to prevent desyncs. */
133  SavedRandomSeeds saved_seeds;
134  SaveRandomSeeds(&saved_seeds);
135 
136  Vehicle *v = nullptr;
137  switch (type) {
138  case VEH_TRAIN: value.AddCost(CmdBuildRailVehicle(subflags, tile, e, use_free_vehicles, &v)); break;
139  case VEH_ROAD: value.AddCost(CmdBuildRoadVehicle(subflags, tile, e, &v)); break;
140  case VEH_SHIP: value.AddCost(CmdBuildShip (subflags, tile, e, &v)); break;
141  case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft (subflags, tile, e, &v)); break;
142  default: NOT_REACHED(); // Safe due to IsDepotTile()
143  }
144 
145  VehicleID veh_id = INVALID_VEHICLE;
146  uint refitted_capacity = 0;
147  uint16 refitted_mail_capacity = 0;
148  if (value.Succeeded()) {
149  if (subflags & DC_EXEC) {
150  v->unitnumber = unit_num;
151  v->value = value.GetCost();
152  veh_id = v->index;
153  }
154 
155  if (refitting) {
156  /* Refit only one vehicle. If we purchased an engine, it may have gained free wagons. */
157  CommandCost cc;
158  std::tie(cc, refitted_capacity, refitted_mail_capacity) = CmdRefitVehicle(flags, v->index, cargo, 0, false, false, 1);
159  value.AddCost(cc);
160  } else {
161  /* Fill in non-refitted capacities */
162  refitted_capacity = e->GetDisplayDefaultCapacity(&refitted_mail_capacity);
163  }
164 
165  if (flags & DC_EXEC) {
169  if (IsLocalCompany()) {
170  InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
171  }
172  }
173 
174  if (subflags & DC_EXEC) {
177 
178  if (v->IsPrimaryVehicle()) {
180  if (!(subflags & DC_AUTOREPLACE)) OrderBackup::Restore(v, client_id);
181  }
182  }
183 
184 
185  /* If we are not in DC_EXEC undo everything */
186  if (flags != subflags) {
188  }
189  }
190 
191  /* Only restore if we actually did some refitting */
192  if (flags != subflags) RestoreRandomSeeds(saved_seeds);
193 
194  return { value, veh_id, refitted_capacity, refitted_mail_capacity };
195 }
196 
206 CommandCost CmdSellVehicle(DoCommandFlag flags, VehicleID v_id, bool sell_chain, bool backup_order, ClientID client_id)
207 {
208  Vehicle *v = Vehicle::GetIfValid(v_id);
209  if (v == nullptr) return CMD_ERROR;
210 
211  Vehicle *front = v->First();
212 
213  CommandCost ret = CheckOwnership(front->owner);
214  if (ret.Failed()) return ret;
215 
216  if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
217 
218  if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
219 
220  /* Can we actually make the order backup, i.e. are there enough orders? */
221  if (backup_order &&
222  front->orders != nullptr &&
223  !front->orders->IsShared() &&
225  /* Only happens in exceptional cases when there aren't enough orders anyhow.
226  * Thus it should be safe to just drop the orders in that case. */
227  backup_order = false;
228  }
229 
230  if (v->type == VEH_TRAIN) {
231  ret = CmdSellRailWagon(flags, v, sell_chain, backup_order, client_id);
232  } else {
233  ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
234 
235  if (flags & DC_EXEC) {
236  if (front->IsPrimaryVehicle() && backup_order) OrderBackup::Backup(front, client_id);
237  delete front;
238  }
239  }
240 
241  return ret;
242 }
243 
253 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
254 {
255  /* Prepare callback param with info about the new cargo type. */
256  const Engine *e = Engine::Get(engine_type);
257 
258  /* Is this vehicle a NewGRF vehicle? */
259  if (e->GetGRF() != nullptr) {
260  const CargoSpec *cs = CargoSpec::Get(new_cid);
261  uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
262 
263  uint16 cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
264  if (cb_res != CALLBACK_FAILED) {
265  *auto_refit_allowed = HasBit(cb_res, 14);
266  int factor = GB(cb_res, 0, 14);
267  if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
268  return factor;
269  }
270  }
271 
272  *auto_refit_allowed = e->info.refit_cost == 0;
273  return (v == nullptr || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
274 }
275 
285 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
286 {
287  ExpensesType expense_type;
288  const Engine *e = Engine::Get(engine_type);
289  Price base_price;
290  int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
291  switch (e->type) {
292  case VEH_SHIP:
293  base_price = PR_BUILD_VEHICLE_SHIP;
294  expense_type = EXPENSES_SHIP_RUN;
295  break;
296 
297  case VEH_ROAD:
298  base_price = PR_BUILD_VEHICLE_ROAD;
299  expense_type = EXPENSES_ROADVEH_RUN;
300  break;
301 
302  case VEH_AIRCRAFT:
303  base_price = PR_BUILD_VEHICLE_AIRCRAFT;
304  expense_type = EXPENSES_AIRCRAFT_RUN;
305  break;
306 
307  case VEH_TRAIN:
308  base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
309  cost_factor <<= 1;
310  expense_type = EXPENSES_TRAIN_RUN;
311  break;
312 
313  default: NOT_REACHED();
314  }
315  if (cost_factor < 0) {
316  return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
317  } else {
318  return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
319  }
320 }
321 
323 struct RefitResult {
325  uint capacity;
327  byte subtype;
328 };
329 
342 static std::tuple<CommandCost, uint, uint16> RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
343 {
344  CommandCost cost(v->GetExpenseType(false));
345  uint total_capacity = 0;
346  uint total_mail_capacity = 0;
347  num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
348 
349  VehicleSet vehicles_to_refit;
350  if (!only_this) {
351  GetVehicleSet(vehicles_to_refit, v, num_vehicles);
352  /* In this case, we need to check the whole chain. */
353  v = v->First();
354  }
355 
356  std::vector<RefitResult> refit_result;
357 
359  byte actual_subtype = new_subtype;
360  for (; v != nullptr; v = (only_this ? nullptr : v->Next())) {
361  /* Reset actual_subtype for every new vehicle */
362  if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
363 
364  if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end() && !only_this) continue;
365 
366  const Engine *e = v->GetEngine();
367  if (!e->CanCarryCargo()) continue;
368 
369  /* If the vehicle is not refittable, or does not allow automatic refitting,
370  * count its capacity nevertheless if the cargo matches */
371  bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
372  if (!refittable && v->cargo_type != new_cid) continue;
373 
374  /* Determine best fitting subtype if requested */
375  if (actual_subtype == 0xFF) {
376  actual_subtype = GetBestFittingSubType(v, v, new_cid);
377  }
378 
379  /* Back up the vehicle's cargo type */
380  CargoID temp_cid = v->cargo_type;
381  byte temp_subtype = v->cargo_subtype;
382  if (refittable) {
383  v->cargo_type = new_cid;
384  v->cargo_subtype = actual_subtype;
385  }
386 
387  uint16 mail_capacity = 0;
388  uint amount = e->DetermineCapacity(v, &mail_capacity);
389  total_capacity += amount;
390  /* mail_capacity will always be zero if the vehicle is not an aircraft. */
391  total_mail_capacity += mail_capacity;
392 
393  if (!refittable) continue;
394 
395  /* Restore the original cargo type */
396  v->cargo_type = temp_cid;
397  v->cargo_subtype = temp_subtype;
398 
399  bool auto_refit_allowed;
400  CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, actual_subtype, &auto_refit_allowed);
401  if (auto_refit && (flags & DC_QUERY_COST) == 0 && !auto_refit_allowed) {
402  /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total.
403  * When querrying cost/capacity (for example in order refit GUI), we always assume 'allowed'.
404  * It is not predictable. */
405  total_capacity -= amount;
406  total_mail_capacity -= mail_capacity;
407 
408  if (v->cargo_type == new_cid) {
409  /* Add the old capacity nevertheless, if the cargo matches */
410  total_capacity += v->cargo_cap;
411  if (v->type == VEH_AIRCRAFT) total_mail_capacity += v->Next()->cargo_cap;
412  }
413  continue;
414  }
415  cost.AddCost(refit_cost);
416 
417  /* Record the refitting.
418  * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
419  * (weird NewGRFs)
420  * Note:
421  * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
422  * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
423  * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
424  * autorefit to behave the same, and we need its result for auto_refit_allowed.
425  */
426  refit_result.push_back({v, amount, mail_capacity, actual_subtype});
427  }
428 
429  if (flags & DC_EXEC) {
430  /* Store the result */
431  for (RefitResult &result : refit_result) {
432  Vehicle *u = result.v;
433  u->refit_cap = (u->cargo_type == new_cid) ? std::min<uint16>(result.capacity, u->refit_cap) : 0;
434  if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
435  u->cargo_type = new_cid;
436  u->cargo_cap = result.capacity;
437  u->cargo_subtype = result.subtype;
438  if (u->type == VEH_AIRCRAFT) {
439  Vehicle *w = u->Next();
440  w->refit_cap = std::min<uint16>(w->refit_cap, result.mail_capacity);
441  w->cargo_cap = result.mail_capacity;
442  if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
443  }
444  }
445  }
446 
447  refit_result.clear();
448  return { cost, total_capacity, total_mail_capacity };
449 }
450 
463 std::tuple<CommandCost, uint, uint16> CmdRefitVehicle(DoCommandFlag flags, VehicleID veh_id, CargoID new_cid, byte new_subtype, bool auto_refit, bool only_this, uint8 num_vehicles)
464 {
465  Vehicle *v = Vehicle::GetIfValid(veh_id);
466  if (v == nullptr) return { CMD_ERROR, 0, 0 };
467 
468  /* Don't allow disasters and sparks and such to be refitted.
469  * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
470  if (!IsCompanyBuildableVehicleType(v->type)) return { CMD_ERROR, 0, 0 };
471 
472  Vehicle *front = v->First();
473 
474  CommandCost ret = CheckOwnership(front->owner);
475  if (ret.Failed()) return { ret, 0, 0 };
476 
477  bool free_wagon = v->type == VEH_TRAIN && Train::From(front)->IsFreeWagon(); // used by autoreplace/renew
478 
479  /* Don't allow shadows and such to be refitted. */
480  if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return { CMD_ERROR, 0, 0 };
481 
482  /* Allow auto-refitting only during loading and normal refitting only in a depot. */
483  if ((flags & DC_QUERY_COST) == 0 && // used by the refit GUI, including the order refit GUI.
484  !free_wagon && // used by autoreplace/renew
485  (!auto_refit || !front->current_order.IsType(OT_LOADING)) && // refit inside stations
486  !front->IsStoppedInDepot()) { // refit inside depots
487  return { CommandCost(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type), 0, 0};
488  }
489 
490  if (front->vehstatus & VS_CRASHED) return { CommandCost(STR_ERROR_VEHICLE_IS_DESTROYED), 0, 0};
491 
492  /* Check cargo */
493  if (new_cid >= NUM_CARGO) return { CMD_ERROR, 0, 0 };
494 
495  /* For ships and aircraft there is always only one. */
496  only_this |= front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
497 
498  auto [cost, refit_capacity, mail_capacity] = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
499 
500  if (flags & DC_EXEC) {
501  /* Update the cached variables */
502  switch (v->type) {
503  case VEH_TRAIN:
504  Train::From(front)->ConsistChanged(auto_refit ? CCF_AUTOREFIT : CCF_REFIT);
505  break;
506  case VEH_ROAD:
507  RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
509  break;
510 
511  case VEH_SHIP:
513  Ship::From(v)->UpdateCache();
514  break;
515 
516  case VEH_AIRCRAFT:
519  break;
520 
521  default: NOT_REACHED();
522  }
523  front->MarkDirty();
524 
525  if (!free_wagon) {
528  }
530  } else {
531  /* Always invalidate the cache; querycost might have filled it. */
533  }
534 
535  return { cost, refit_capacity, mail_capacity };
536 }
537 
545 CommandCost CmdStartStopVehicle(DoCommandFlag flags, VehicleID veh_id, bool evaluate_startstop_cb)
546 {
547  /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
548  if ((flags & DC_AUTOREPLACE) == 0) evaluate_startstop_cb = true;
549 
550  Vehicle *v = Vehicle::GetIfValid(veh_id);
551  if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
552 
553  CommandCost ret = CheckOwnership(v->owner);
554  if (ret.Failed()) return ret;
555 
556  if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
557 
558  switch (v->type) {
559  case VEH_TRAIN:
560  if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER);
561  break;
562 
563  case VEH_SHIP:
564  case VEH_ROAD:
565  break;
566 
567  case VEH_AIRCRAFT: {
568  Aircraft *a = Aircraft::From(v);
569  /* cannot stop airplane when in flight, or when taking off / landing */
570  if (a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
571  if (HasBit(a->flags, VAF_HELI_DIRECT_DESCENT)) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
572  break;
573  }
574 
575  default: return CMD_ERROR;
576  }
577 
578  if (evaluate_startstop_cb) {
579  /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
580  uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
581  StringID error = STR_NULL;
582  if (callback != CALLBACK_FAILED) {
583  if (v->GetGRF()->grf_version < 8) {
584  /* 8 bit result 0xFF means 'allow' */
585  if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
586  } else {
587  if (callback < 0x400) {
588  error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
589  } else {
590  switch (callback) {
591  case 0x400: // allow
592  break;
593 
594  default: // unknown reason -> disallow
595  error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
596  break;
597  }
598  }
599  }
600  }
601  if (error != STR_NULL) return_cmd_error(error);
602  }
603 
604  if (flags & DC_EXEC) {
605  if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(veh_id, STR_NEWS_TRAIN_IS_WAITING + v->type);
606 
607  v->vehstatus ^= VS_STOPPED;
608  if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
609  v->MarkDirty();
614  }
615  return CommandCost();
616 }
617 
627 CommandCost CmdMassStartStopVehicle(DoCommandFlag flags, TileIndex tile, bool do_start, bool vehicle_list_window, const VehicleListIdentifier &vli)
628 {
629  VehicleList list;
630 
631  if (!vli.Valid()) return CMD_ERROR;
633 
634  if (vehicle_list_window) {
635  if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
636  } else {
637  if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
638  /* Get the list of vehicles in the depot */
639  BuildDepotVehicleList(vli.vtype, tile, &list, nullptr);
640  }
641 
642  for (uint i = 0; i < list.size(); i++) {
643  const Vehicle *v = list[i];
644 
645  if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
646 
647  if (!vehicle_list_window && !v->IsChainInDepot()) continue;
648 
649  /* Just try and don't care if some vehicle's can't be stopped. */
650  Command<CMD_START_STOP_VEHICLE>::Do(flags, v->index, false);
651  }
652 
653  return CommandCost();
654 }
655 
664 {
665  VehicleList list;
666 
668 
669  if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
670  if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
671 
672  /* Get the list of vehicles in the depot */
673  BuildDepotVehicleList(vehicle_type, tile, &list, &list);
674 
675  CommandCost last_error = CMD_ERROR;
676  bool had_success = false;
677  for (uint i = 0; i < list.size(); i++) {
678  CommandCost ret = Command<CMD_SELL_VEHICLE>::Do(flags, list[i]->index, true, false, INVALID_CLIENT_ID);
679  if (ret.Succeeded()) {
680  cost.AddCost(ret);
681  had_success = true;
682  } else {
683  last_error = ret;
684  }
685  }
686 
687  return had_success ? cost : last_error;
688 }
689 
698 {
699  VehicleList list;
701 
702  if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
703  if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
704 
705  /* Get the list of vehicles in the depot */
706  BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
707 
708  for (uint i = 0; i < list.size(); i++) {
709  const Vehicle *v = list[i];
710 
711  /* Ensure that the vehicle completely in the depot */
712  if (!v->IsChainInDepot()) continue;
713 
715 
716  if (ret.Succeeded()) cost.AddCost(ret);
717  }
718  return cost;
719 }
720 
726 static bool IsUniqueVehicleName(const std::string &name)
727 {
728  for (const Vehicle *v : Vehicle::Iterate()) {
729  if (!v->name.empty() && v->name == name) return false;
730  }
731 
732  return true;
733 }
734 
740 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
741 {
742  std::string buf;
743 
744  /* Find the position of the first digit in the last group of digits. */
745  size_t number_position;
746  for (number_position = src->name.length(); number_position > 0; number_position--) {
747  /* The design of UTF-8 lets this work simply without having to check
748  * for UTF-8 sequences. */
749  if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
750  }
751 
752  /* Format buffer and determine starting number. */
753  long num;
754  byte padding = 0;
755  if (number_position == src->name.length()) {
756  /* No digit at the end, so start at number 2. */
757  buf = src->name;
758  buf += " ";
759  number_position = buf.length();
760  num = 2;
761  } else {
762  /* Found digits, parse them and start at the next number. */
763  buf = src->name.substr(0, number_position);
764 
765  auto num_str = src->name.substr(number_position);
766  padding = (byte)num_str.length();
767 
768  std::istringstream iss(num_str);
769  iss >> num;
770  num++;
771  }
772 
773  /* Check if this name is already taken. */
774  for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
775  std::ostringstream oss;
776 
777  /* Attach the number to the temporary name. */
778  oss << buf << std::setw(padding) << std::setfill('0') << std::internal << num;
779 
780  /* Check the name is unique. */
781  auto new_name = oss.str();
782  if (IsUniqueVehicleName(new_name)) {
783  dst->name = new_name;
784  break;
785  }
786  }
787 
788  /* All done. If we didn't find a name, it'll just use its default. */
789 }
790 
799 std::tuple<CommandCost, VehicleID> CmdCloneVehicle(DoCommandFlag flags, TileIndex tile, VehicleID veh_id, bool share_orders)
800 {
802 
803  Vehicle *v = Vehicle::GetIfValid(veh_id);
804  if (v == nullptr || !v->IsPrimaryVehicle()) return { CMD_ERROR, INVALID_VEHICLE };
805  Vehicle *v_front = v;
806  Vehicle *w = nullptr;
807  Vehicle *w_front = nullptr;
808  Vehicle *w_rear = nullptr;
809 
810  /*
811  * v_front is the front engine in the original vehicle
812  * v is the car/vehicle of the original vehicle that is currently being copied
813  * w_front is the front engine of the cloned vehicle
814  * w is the car/vehicle currently being cloned
815  * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
816  */
817 
818  CommandCost ret = CheckOwnership(v->owner);
819  if (ret.Failed()) return { ret, INVALID_VEHICLE };
820 
821  if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return { CMD_ERROR, INVALID_VEHICLE };
822 
823  /* check that we can allocate enough vehicles */
824  if (!(flags & DC_EXEC)) {
825  int veh_counter = 0;
826  do {
827  veh_counter++;
828  } while ((v = v->Next()) != nullptr);
829 
830  if (!Vehicle::CanAllocateItem(veh_counter)) {
831  return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE };
832  }
833  }
834 
835  v = v_front;
836 
837  VehicleID new_veh_id = INVALID_VEHICLE;
838  do {
839  if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
840  /* we build the rear ends of multiheaded trains with the front ones */
841  continue;
842  }
843 
844  /* In case we're building a multi headed vehicle and the maximum number of
845  * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
846  * be cloned. When the non-primary engines were build they were seen as
847  * 'new' vehicles whereas they would immediately be joined with a primary
848  * engine. This caused the vehicle to be not build as 'the limit' had been
849  * reached, resulting in partially build vehicles and such. */
850  DoCommandFlag build_flags = flags;
851  if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
852 
853  CommandCost cost;
854  std::tie(cost, new_veh_id, std::ignore, std::ignore) = Command<CMD_BUILD_VEHICLE>::Do(build_flags, tile, v->engine_type, false, CT_INVALID, INVALID_CLIENT_ID);
855 
856  if (cost.Failed()) {
857  /* Can't build a part, then sell the stuff we already made; clear up the mess */
858  if (w_front != nullptr) Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
859  return { cost, INVALID_VEHICLE };
860  }
861 
862  total_cost.AddCost(cost);
863 
864  if (flags & DC_EXEC) {
865  w = Vehicle::Get(new_veh_id);
866 
867  if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
869  }
870 
871  if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
872  /* this s a train car
873  * add this unit to the end of the train */
874  CommandCost result = Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags, w->index, w_rear->index, true);
875  if (result.Failed()) {
876  /* The train can't be joined to make the same consist as the original.
877  * Sell what we already made (clean up) and return an error. */
878  Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
879  Command<CMD_SELL_VEHICLE>::Do(flags, w->index, true, false, INVALID_CLIENT_ID);
880  return { result, INVALID_VEHICLE }; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
881  }
882  } else {
883  /* this is a front engine or not a train. */
884  w_front = w;
886  w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
887  w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
888  }
889  w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
890  }
891  } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
892 
893  if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
894  /* for trains this needs to be the front engine due to the callback function */
895  new_veh_id = w_front->index;
896  }
897 
898  if (flags & DC_EXEC) {
899  /* Cloned vehicles belong to the same group */
900  Command<CMD_ADD_VEHICLE_GROUP>::Do(flags, v_front->group_id, w_front->index, false);
901  }
902 
903 
904  /* Take care of refitting. */
905  w = w_front;
906  v = v_front;
907 
908  /* Both building and refitting are influenced by newgrf callbacks, which
909  * makes it impossible to accurately estimate the cloning costs. In
910  * particular, it is possible for engines of the same type to be built with
911  * different numbers of articulated parts, so when refitting we have to
912  * loop over real vehicles first, and then the articulated parts of those
913  * vehicles in a different loop. */
914  do {
915  do {
916  if (flags & DC_EXEC) {
917  assert(w != nullptr);
918 
919  /* Find out what's the best sub type */
920  byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
921  if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
922  CommandCost cost = std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(flags, w->index, v->cargo_type, subtype, false, true, 0));
923  if (cost.Succeeded()) total_cost.AddCost(cost);
924  }
925 
926  if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
927  w = w->GetNextArticulatedPart();
928  } else {
929  break;
930  }
931  } else {
932  const Engine *e = v->GetEngine();
933  CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
934 
935  if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
936  bool dummy;
937  total_cost.AddCost(GetRefitCost(nullptr, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
938  }
939  }
940 
941  if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
942  v = v->GetNextArticulatedPart();
943  } else {
944  break;
945  }
946  } while (v != nullptr);
947 
948  if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
949  } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
950 
951  if (flags & DC_EXEC) {
952  /*
953  * Set the orders of the vehicle. Cannot do it earlier as we need
954  * the vehicle refitted before doing this, otherwise the moved
955  * cargo types might not match (passenger vs non-passenger)
956  */
957  CommandCost result = Command<CMD_CLONE_ORDER>::Do(flags, (share_orders ? CO_SHARE : CO_COPY), w_front->index, v_front->index);
958  if (result.Failed()) {
959  /* The vehicle has already been bought, so now it must be sold again. */
960  Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
961  return { total_cost, INVALID_VEHICLE };
962  }
963 
964  /* Now clone the vehicle's name, if it has one. */
965  if (!v_front->name.empty()) CloneVehicleName(v_front, w_front);
966 
967  /* Since we can't estimate the cost of cloning a vehicle accurately we must
968  * check whether the company has enough money manually. */
969  if (!CheckCompanyHasMoney(total_cost)) {
970  /* The vehicle has already been bought, so now it must be sold again. */
971  Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
972  return { total_cost, INVALID_VEHICLE };
973  }
974  }
975 
976  return { total_cost, new_veh_id };
977 }
978 
987 {
988  VehicleList list;
989 
990  if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
991 
992  /* Send all the vehicles to a depot */
993  bool had_success = false;
994  for (uint i = 0; i < list.size(); i++) {
995  const Vehicle *v = list[i];
997 
998  if (ret.Succeeded()) {
999  had_success = true;
1000 
1001  /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
1002  * In this case we know that at least one vehicle can be sent to a depot
1003  * and we will issue the command. We can now safely quit the loop, knowing
1004  * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
1005  if (!(flags & DC_EXEC)) break;
1006  }
1007  }
1008 
1009  return had_success ? CommandCost() : CMD_ERROR;
1010 }
1011 
1021 {
1022  if ((depot_cmd & DepotCommand::MassSend) != DepotCommand::None) {
1023  /* Mass goto depot requested */
1024  if (!vli.Valid()) return CMD_ERROR;
1025  return SendAllVehiclesToDepot(flags, (depot_cmd & DepotCommand::Service) != DepotCommand::None, vli);
1026  }
1027 
1028  Vehicle *v = Vehicle::GetIfValid(veh_id);
1029  if (v == nullptr) return CMD_ERROR;
1030  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
1031 
1032  return v->SendToDepot(flags, depot_cmd);
1033 }
1034 
1042 CommandCost CmdRenameVehicle(DoCommandFlag flags, VehicleID veh_id, const std::string &text)
1043 {
1044  Vehicle *v = Vehicle::GetIfValid(veh_id);
1045  if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1046 
1047  CommandCost ret = CheckOwnership(v->owner);
1048  if (ret.Failed()) return ret;
1049 
1050  bool reset = text.empty();
1051 
1052  if (!reset) {
1054  if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1055  }
1056 
1057  if (flags & DC_EXEC) {
1058  if (reset) {
1059  v->name.clear();
1060  } else {
1061  v->name = text;
1062  }
1065  }
1066 
1067  return CommandCost();
1068 }
1069 
1070 
1080 CommandCost CmdChangeServiceInt(DoCommandFlag flags, VehicleID veh_id, uint16 serv_int, bool is_custom, bool is_percent)
1081 {
1082  Vehicle *v = Vehicle::GetIfValid(veh_id);
1083  if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1084 
1085  CommandCost ret = CheckOwnership(v->owner);
1086  if (ret.Failed()) return ret;
1087 
1088  const Company *company = Company::Get(v->owner);
1089  is_percent = is_custom ? is_percent : company->settings.vehicle.servint_ispercent;
1090 
1091  if (is_custom) {
1092  if (serv_int != GetServiceIntervalClamped(serv_int, is_percent)) return CMD_ERROR;
1093  } else {
1094  serv_int = CompanyServiceInterval(company, v->type);
1095  }
1096 
1097  if (flags & DC_EXEC) {
1098  v->SetServiceInterval(serv_int);
1099  v->SetServiceIntervalIsCustom(is_custom);
1100  v->SetServiceIntervalIsPercent(is_percent);
1102  }
1103 
1104  return CommandCost();
1105 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
VehicleCargoList::TotalCount
uint TotalCount() const
Returns sum of cargo, including reserved cargo.
Definition: cargopacket.h:361
Vehicle::IsChainInDepot
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
Definition: vehicle_base.h:527
Engine::GetDisplayDefaultCapacity
uint GetDisplayDefaultCapacity(uint16 *mail_capacity=nullptr) const
Determines the default cargo capacity of an engine for display purposes.
Definition: engine_base.h:103
IsCompanyBuildableVehicleType
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Definition: vehicle_func.h:89
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3234
EXPENSES_ROADVEH_RUN
@ EXPENSES_ROADVEH_RUN
Running costs road vehicles.
Definition: economy_type.h:161
RefitResult::mail_capacity
uint mail_capacity
New mail capacity of aircraft.
Definition: vehicle_cmd.cpp:326
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:71
order_cmd.h
VehicleList
std::vector< const Vehicle * > VehicleList
A list of vehicles.
Definition: vehiclelist.h:55
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3136
INVALID_CLIENT_ID
@ INVALID_CLIENT_ID
Client is not part of anything.
Definition: network_type.h:48
GetServiceIntervalClamped
uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
Clamp the service interval to the correct min/max.
Definition: order_cmd.cpp:1878
GroupStatistics::CountEngine
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
Definition: group_cmd.cpp:154
GetPrice
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:965
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
Vehicle::value
Money value
Value of the vehicle.
Definition: vehicle_base.h:256
train.h
AircraftVehicleInfo::subtype
byte subtype
Type of aircraft.
Definition: engine_type.h:102
command_func.h
CBID_VEHICLE_START_STOP_CHECK
@ CBID_VEHICLE_START_STOP_CHECK
Called when the company (or AI) tries to start or stop a vehicle.
Definition: newgrf_callbacks.h:141
Pool::PoolItem<&_vehicle_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:348
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
VehicleListIdentifier
The information about a vehicle list.
Definition: vehiclelist.h:29
Vehicle::GetNextVehicle
Vehicle * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
Definition: vehicle_base.h:974
CmdRenameVehicle
CommandCost CmdRenameVehicle(DoCommandFlag flags, VehicleID veh_id, const std::string &text)
Give a custom name to your vehicle.
Definition: vehicle_cmd.cpp:1042
company_base.h
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:600
SendAllVehiclesToDepot
static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
Send all vehicles of type to depots.
Definition: vehicle_cmd.cpp:986
UnitID
uint16 UnitID
Type for the company global vehicle unit number.
Definition: transport_type.h:16
CmdMassStartStopVehicle
CommandCost CmdMassStartStopVehicle(DoCommandFlag flags, TileIndex tile, bool do_start, bool vehicle_list_window, const VehicleListIdentifier &vli)
Starts or stops a lot of vehicles.
Definition: vehicle_cmd.cpp:627
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:74
CmdRefitVehicle
std::tuple< CommandCost, uint, uint16 > CmdRefitVehicle(DoCommandFlag flags, VehicleID veh_id, CargoID new_cid, byte new_subtype, bool auto_refit, bool only_this, uint8 num_vehicles)
Refits a vehicle to the specified cargo type.
Definition: vehicle_cmd.cpp:463
vehiclelist.h
GetVehicleSet
void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8 num_vehicles)
Calculates the set of vehicles that will be affected by a given selection.
Definition: vehicle.cpp:2969
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:332
BaseConsist::name
std::string name
Name of vehicle.
Definition: base_consist.h:19
SavedRandomSeeds
Stores the state of all random number generators.
Definition: random_func.hpp:33
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
Train::crash_anim_pos
uint16 crash_anim_pos
Crash animation counter.
Definition: train.h:92
Vehicle::group_id
GroupID group_id
Index of group Pool array.
Definition: vehicle_base.h:341
DeleteVehicleNews
void DeleteVehicleNews(VehicleID vid, StringID news)
Delete a news item type about a vehicle.
Definition: news_gui.cpp:917
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
GroupStatistics::CountVehicle
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
Definition: group_cmd.cpp:131
ship.h
SaveRandomSeeds
static void SaveRandomSeeds(SavedRandomSeeds *storage)
Saves the current seeds.
Definition: random_func.hpp:42
group.h
CompanySettings::vehicle
VehicleDefaultSettings vehicle
default settings for vehicles
Definition: settings_type.h:575
TileIndex
The index/ID of a Tile.
Definition: tile_type.h:85
CmdBuildShip
CommandCost CmdBuildShip(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a ship.
Definition: ship_cmd.cpp:861
Vehicle::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:751
EXPENSES_AIRCRAFT_RUN
@ EXPENSES_AIRCRAFT_RUN
Running costs aircraft.
Definition: economy_type.h:162
autoreplace_gui.h
aircraft.h
CmdDepotMassAutoReplace
CommandCost CmdDepotMassAutoReplace(DoCommandFlag flags, TileIndex tile, VehicleType vehicle_type)
Autoreplace all vehicles in the depot.
Definition: vehicle_cmd.cpp:697
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:57
GroundVehicle::IsRearDualheaded
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Definition: ground_vehicle.hpp:334
CCF_REFIT
@ CCF_REFIT
Valid changes for refitting in a depot.
Definition: train.h:51
WC_COMPANY
@ WC_COMPANY
Company view; Window numbers:
Definition: window_type.h:361
Vehicle::GetNextArticulatedPart
Vehicle * GetNextArticulatedPart() const
Get the next part of an articulated engine.
Definition: vehicle_base.h:931
Engine
Definition: engine_base.h:27
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
Vehicle::cur_speed
uint16 cur_speed
current speed
Definition: vehicle_base.h:307
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:224
Vehicle::IsPrimaryVehicle
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:450
Vehicle::IsGroundVehicle
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
Definition: vehicle_base.h:488
OrderList::IsShared
bool IsShared() const
Is this a shared order list?
Definition: order_base.h:341
Engine::GetDefaultCargoType
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition: engine_base.h:83
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:288
GetVehicleCallback
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
Definition: newgrf_engine.cpp:1160
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:350
aircraft_cmd.h
IsLocalCompany
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:43
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:348
CountArticulatedParts
uint CountArticulatedParts(EngineID engine_type, bool purchase_window)
Count the number of articulated parts of an engine.
Definition: articulated_vehicles.cpp:73
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:151
TERM7
@ TERM7
Heading for terminal 7.
Definition: airport.h:80
RestoreRandomSeeds
static void RestoreRandomSeeds(const SavedRandomSeeds &storage)
Restores previously saved seeds.
Definition: random_func.hpp:52
train_cmd.h
IsDepotTile
static bool IsDepotTile(TileIndex tile)
Is the given tile a tile with a depot on it?
Definition: depot_map.h:41
Vehicle::IsArticulatedPart
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:912
DepotCommand::Service
@ Service
The vehicle will leave the depot right after arrival (service only)
Aircraft
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition: aircraft.h:74
Ship::UpdateCache
void UpdateCache()
Update the caches of this ship.
Definition: ship_cmd.cpp:203
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:142
SetWindowWidgetDirty
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition: window.cpp:3149
GetRefitCostFactor
static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
Helper to run the refit cost callback.
Definition: vehicle_cmd.cpp:253
Utf8StringLength
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition: string.cpp:435
CBID_VEHICLE_REFIT_COST
@ CBID_VEHICLE_REFIT_COST
Called to determine the cost factor for refitting a vehicle.
Definition: newgrf_callbacks.h:275
EngineID
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
DepotCommand
DepotCommand
Flags for goto depot commands.
Definition: vehicle_type.h:65
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition: company_cmd.cpp:313
EF_AUTO_REFIT
@ EF_AUTO_REFIT
Automatic refitting is allowed.
Definition: engine_type.h:159
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
ship_cmd.h
CommandCost
Common return value for all commands.
Definition: command_type.h:24
VAF_HELI_DIRECT_DESCENT
@ VAF_HELI_DIRECT_DESCENT
The helicopter is descending directly at its destination (helipad or in front of hangar)
Definition: aircraft.h:47
CmdBuildRailVehicle
CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, bool free_cars, Vehicle **ret)
Build a railroad vehicle.
Definition: train_cmd.cpp:723
CmdDepotSellAllVehicles
CommandCost CmdDepotSellAllVehicles(DoCommandFlag flags, TileIndex tile, VehicleType vehicle_type)
Sells all vehicles in a depot.
Definition: vehicle_cmd.cpp:663
VehicleCargoList::Truncate
uint Truncate(uint max_move=UINT_MAX)
Truncates the cargo in this list to the given amount.
Definition: cargopacket.cpp:654
WC_VEHICLE_VIEW
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
Definition: window_type.h:331
GetRefitCost
static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
Learn the price of refitting a certain engine.
Definition: vehicle_cmd.cpp:285
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:245
INVALID_VEHICLE
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
Definition: vehicle_type.h:55
DepotCommand::MassSend
@ MassSend
Tells that it's a mass send to depot command (type in VLW flag)
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:302
VS_CRASHED
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:41
do_start
bool do_start
flag for starting playback of next_file at next opportunity
Definition: dmusic.cpp:126
ClientID
ClientID
'Unique' identifier to be given to clients
Definition: network_type.h:47
GetFreeUnitNumber
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Definition: vehicle.cpp:1806
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:324
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:160
Vehicle::GetExpenseType
virtual ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
Definition: vehicle_base.h:440
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:333
GroundVehicle::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition: ground_vehicle.hpp:80
autoreplace_cmd.h
Vehicle::IsFrontEngine
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:903
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:106
DC_AUTOREPLACE
@ DC_AUTOREPLACE
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
Definition: command_type.h:357
WC_VEHICLE_DETAILS
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
Definition: window_type.h:192
VS_STOPPED
@ VS_STOPPED
Vehicle is stopped by the player.
Definition: vehicle_base.h:35
Vehicle::GetGRFID
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:761
CloneVehicleName
static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
Clone the custom name of a vehicle, adding or incrementing a number.
Definition: vehicle_cmd.cpp:740
Vehicle::GetEngine
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:741
BuildDepotVehicleList
void BuildDepotVehicleList(VehicleType type, TileIndex tile, VehicleList *engines, VehicleList *wagons, bool individual_wagons)
Generate a list of vehicles inside a depot.
Definition: vehiclelist.cpp:69
GenerateVehicleSortList
bool GenerateVehicleSortList(VehicleList *list, const VehicleListIdentifier &vli)
Generate a list of vehicles based on window type.
Definition: vehiclelist.cpp:113
safeguards.h
GroupStatistics::UpdateAutoreplace
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:202
RefitResult::v
Vehicle * v
Vehicle to refit.
Definition: vehicle_cmd.cpp:324
vehicle_cmd.h
OrderBackup::Restore
static void Restore(Vehicle *v, uint32 user)
Restore the data of this order to the given vehicle.
Definition: order_backup.cpp:120
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
GetGRFStringID
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:601
IsTileOwner
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
VRF_REVERSE_DIRECTION
@ VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
Definition: train.h:28
newgrf_text.h
Engine::GetCost
Money GetCost() const
Return how much a new engine costs.
Definition: engine.cpp:309
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:63
stdafx.h
Vehicle::SendToDepot
CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command)
Send this vehicle to the depot using the given command(s).
Definition: vehicle.cpp:2387
WID_VV_START_STOP
@ WID_VV_START_STOP
Start or stop this vehicle, and show information about the current state.
Definition: vehicle_widget.h:17
VehicleType
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
CheckCompanyHasMoney
bool CheckCompanyHasMoney(CommandCost &cost)
Verify whether the company can pay the bill.
Definition: company_cmd.cpp:197
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:143
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition: engine_type.h:29
UpdateAircraftCache
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
Definition: aircraft_cmd.cpp:590
group_cmd.h
CmdChangeServiceInt
CommandCost CmdChangeServiceInt(DoCommandFlag flags, VehicleID veh_id, uint16 serv_int, bool is_custom, bool is_percent)
Change the service interval of a vehicle.
Definition: vehicle_cmd.cpp:1080
GetWindowClassForVehicleType
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:91
string_func.h
RefitResult
Helper structure for RefitVehicle()
Definition: vehicle_cmd.cpp:323
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:404
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
CCF_AUTOREFIT
@ CCF_AUTOREFIT
Valid changes for autorefitting in stations.
Definition: train.h:50
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
vehicle_func.h
Pool::PoolItem<&_vehicle_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:386
Vehicle::First
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:613
Vehicle::cargo_cap
uint16 cargo_cap
total capacity
Definition: vehicle_base.h:322
Engine::CanCarryCargo
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:161
RoadVehUpdateCache
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
Definition: roadveh_cmd.cpp:217
MAX_LENGTH_VEHICLE_NAME_CHARS
static const uint MAX_LENGTH_VEHICLE_NAME_CHARS
The maximum length of a vehicle name in characters including '\0'.
Definition: vehicle_type.h:74
GroundVehicleCache::cached_power
uint32 cached_power
Total power of the consist (valid only for the first engine).
Definition: ground_vehicle.hpp:38
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1170
VehicleSettings::roadveh_acceleration_model
uint8 roadveh_acceleration_model
realistic acceleration for road vehicles
Definition: settings_type.h:484
Train::ConsistChanged
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:108
VehicleListIdentifier::vtype
VehicleType vtype
The vehicle type associated with this list.
Definition: vehiclelist.h:31
Vehicle::InvalidateNewGRFCacheOfChain
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
Definition: vehicle_base.h:477
CompanyServiceInterval
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
Definition: company_cmd.cpp:1135
InvalidateWindowClassesData
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition: window.cpp:3251
CmdSendVehicleToDepot
CommandCost CmdSendVehicleToDepot(DoCommandFlag flags, VehicleID veh_id, DepotCommand depot_cmd, const VehicleListIdentifier &vli)
Send a vehicle to the depot.
Definition: vehicle_cmd.cpp:1020
RefitVehicle
static std::tuple< CommandCost, uint, uint16 > RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
Refits a vehicle (chain).
Definition: vehicle_cmd.cpp:342
RAILVEH_MULTIHEAD
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition: engine_type.h:28
WC_VEHICLE_DEPOT
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
Definition: window_type.h:343
CargoSpec::classes
uint16 classes
Classes of this cargo type.
Definition: cargotype.h:79
newgrf.h
NUM_CARGO
@ NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:65
Vehicle::HasArticulatedPart
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Definition: vehicle_base.h:921
CmdSellVehicle
CommandCost CmdSellVehicle(DoCommandFlag flags, VehicleID v_id, bool sell_chain, bool backup_order, ClientID client_id)
Sell a vehicle.
Definition: vehicle_cmd.cpp:206
GRFFile::cargo_map
uint8 cargo_map[NUM_CARGO]
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:127
Pool::PoolItem<&_vehicle_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:307
DepotCommand::DontCancel
@ DontCancel
Don't cancel current goto depot command if any.
Vehicle::unitnumber
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:305
depot_map.h
CmdStartStopVehicle
CommandCost CmdStartStopVehicle(DoCommandFlag flags, VehicleID veh_id, bool evaluate_startstop_cb)
Start/Stop a vehicle.
Definition: vehicle_cmd.cpp:545
company_func.h
IsUniqueVehicleName
static bool IsUniqueVehicleName(const std::string &name)
Test if a name is unique among vehicle names.
Definition: vehicle_cmd.cpp:726
EXPENSES_NEW_VEHICLES
@ EXPENSES_NEW_VEHICLES
New vehicles.
Definition: economy_type.h:159
VehicleID
uint32 VehicleID
The type all our vehicle IDs have.
Definition: vehicle_type.h:16
InvalidateAutoreplaceWindow
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
Definition: autoreplace_gui.cpp:52
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:133
AIR_CTOL
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
Definition: engine_type.h:93
CommandHelper
Definition: command_func.h:94
BaseConsist::service_interval
uint16 service_interval
The interval for (automatic) servicing; either in days or %.
Definition: base_consist.h:26
VehicleDefaultSettings::servint_ispercent
bool servint_ispercent
service intervals are in percents
Definition: settings_type.h:562
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1753
OrderBackup::Backup
static void Backup(const Vehicle *v, uint32 user)
Create an order backup for the given vehicle.
Definition: order_backup.cpp:102
random_func.hpp
EXPENSES_TRAIN_RUN
@ EXPENSES_TRAIN_RUN
Running costs trains.
Definition: economy_type.h:160
STARTTAKEOFF
@ STARTTAKEOFF
Airplane has arrived at a runway for take-off.
Definition: airport.h:72
Engine::DetermineCapacity
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition: engine.cpp:194
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
Vehicle::IsStoppedInDepot
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition: vehicle_base.h:533
CmdBuildRoadVehicle
CommandCost CmdBuildRoadVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a road vehicle.
Definition: roadveh_cmd.cpp:260
GroundVehicle::CargoChanged
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
Definition: ground_vehicle.cpp:79
CmdSellRailWagon
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
Sell a (single) train wagon/engine.
Definition: train_cmd.cpp:1358
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:320
Aircraft::state
byte state
State of the airport.
Definition: aircraft.h:79
airport.h
articulated_vehicles.h
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:589
Vehicle::cargo_subtype
byte cargo_subtype
Used for livery refits (NewGRF variations)
Definition: vehicle_base.h:321
GroundVehicle::IsFreeWagon
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
Definition: ground_vehicle.hpp:310
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
CmdBuildVehicle
std::tuple< CommandCost, VehicleID, uint, uint16 > CmdBuildVehicle(DoCommandFlag flags, TileIndex tile, EngineID eid, bool use_free_vehicles, CargoID cargo, ClientID client_id)
Build a vehicle.
Definition: vehicle_cmd.cpp:87
RefitResult::capacity
uint capacity
New capacity of vehicle.
Definition: vehicle_cmd.cpp:325
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
DC_QUERY_COST
@ DC_QUERY_COST
query cost only, don't build.
Definition: command_type.h:352
RefitResult::subtype
byte subtype
cargo subtype to refit to
Definition: vehicle_cmd.cpp:327
ExpensesType
ExpensesType
Types of expenses.
Definition: economy_type.h:157
order_backup.h
CT_INVALID
@ CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:69
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
Company
Definition: company_base.h:117
CmdCloneVehicle
std::tuple< CommandCost, VehicleID > CmdCloneVehicle(DoCommandFlag flags, TileIndex tile, VehicleID veh_id, bool share_orders)
Clone a vehicle.
Definition: vehicle_cmd.cpp:799
DepotCommand::None
@ None
No special flags.
Vehicle::orders
OrderList * orders
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:336
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3162
Aircraft::flags
byte flags
Aircraft flags.
Definition: aircraft.h:83
roadveh_cmd.h
IsEngineBuildable
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition: engine.cpp:1105
GetBestFittingSubType
byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
Get the best fitting subtype when 'cloning'/'replacing' v_from with v_for.
Definition: vehicle_gui.cpp:322
OrderList::GetNumOrders
VehicleOrderID GetNumOrders() const
Get number of orders in the order list.
Definition: order_base.h:322
EXPENSES_SHIP_RUN
@ EXPENSES_SHIP_RUN
Running costs ships.
Definition: economy_type.h:163
CmdBuildAircraft
CommandCost CmdBuildAircraft(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build an aircraft.
Definition: aircraft_cmd.cpp:269
Vehicle::MarkDirty
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: vehicle_base.h:381
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:46
Vehicle::refit_cap
uint16 refit_cap
Capacity left over from before last refit.
Definition: vehicle_base.h:323
engine_func.h
news_func.h
roadveh.h
GetDepotVehicleType
static VehicleType GetDepotVehicleType(TileIndex t)
Get the type of vehicles that can use a depot.
Definition: depot_map.h:65