OpenTTD Source  1.10.2
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 "cmd_helper.h"
15 #include "command_func.h"
16 #include "company_func.h"
17 #include "train.h"
18 #include "aircraft.h"
19 #include "newgrf_text.h"
20 #include "vehicle_func.h"
21 #include "string_func.h"
22 #include "depot_map.h"
23 #include "vehiclelist.h"
24 #include "engine_func.h"
25 #include "articulated_vehicles.h"
26 #include "autoreplace_gui.h"
27 #include "group.h"
28 #include "order_backup.h"
29 #include "ship.h"
30 #include "newgrf.h"
31 #include "company_base.h"
32 #include "core/random_func.hpp"
33 
34 #include "table/strings.h"
35 
36 #include "safeguards.h"
37 
38 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
39 const uint32 _veh_build_proc_table[] = {
40  CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
41  CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
42  CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
43  CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT),
44 };
45 
46 const uint32 _veh_sell_proc_table[] = {
47  CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_TRAIN),
48  CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_ROAD_VEHICLE),
49  CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_SHIP),
50  CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_AIRCRAFT),
51 };
52 
53 const uint32 _veh_refit_proc_table[] = {
54  CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_TRAIN),
55  CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE),
56  CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_SHIP),
57  CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_AIRCRAFT),
58 };
59 
60 const uint32 _send_to_depot_proc_table[] = {
61  CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT),
62  CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT),
63  CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT),
64  CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR),
65 };
66 
67 
68 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
69 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
70 CommandCost CmdBuildShip (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
71 CommandCost CmdBuildAircraft (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
72 
73 CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text);
74 
87 CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
88 {
89  /* Elementary check for valid location. */
90  if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
91 
92  VehicleType type = GetDepotVehicleType(tile);
93 
94  /* Validate the engine type. */
95  EngineID eid = GB(p1, 0, 16);
96  if (!IsEngineBuildable(eid, type, _current_company)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type);
97 
98  /* Validate the cargo type. */
99  CargoID cargo = GB(p1, 24, 8);
100  if (cargo >= NUM_CARGO && cargo != CT_INVALID) return CMD_ERROR;
101 
102  const Engine *e = Engine::Get(eid);
104 
105  /* Engines without valid cargo should not be available */
106  CargoID default_cargo = e->GetDefaultCargoType();
107  if (default_cargo == CT_INVALID) return CMD_ERROR;
108 
109  bool refitting = cargo != CT_INVALID && cargo != default_cargo;
110 
111  /* Check whether the number of vehicles we need to build can be built according to pool space. */
112  uint num_vehicles;
113  switch (type) {
114  case VEH_TRAIN: num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
115  case VEH_ROAD: num_vehicles = 1 + CountArticulatedParts(eid, false); break;
116  case VEH_SHIP: num_vehicles = 1; break;
117  case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
118  default: NOT_REACHED(); // Safe due to IsDepotTile()
119  }
120  if (!Vehicle::CanAllocateItem(num_vehicles)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
121 
122  /* Check whether we can allocate a unit number. Autoreplace does not allocate
123  * an unit number as it will (always) reuse the one of the replaced vehicle
124  * and (train) wagons don't have an unit number in any scenario. */
125  UnitID unit_num = (flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
126  if (unit_num == UINT16_MAX) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
127 
128  /* If we are refitting we need to temporarily purchase the vehicle to be able to
129  * test it. */
130  DoCommandFlag subflags = flags;
131  if (refitting && !(flags & DC_EXEC)) subflags |= DC_EXEC | DC_AUTOREPLACE;
132 
133  /* Vehicle construction needs random bits, so we have to save the random
134  * seeds to prevent desyncs. */
135  SavedRandomSeeds saved_seeds;
136  SaveRandomSeeds(&saved_seeds);
137 
138  Vehicle *v = nullptr;
139  switch (type) {
140  case VEH_TRAIN: value.AddCost(CmdBuildRailVehicle(tile, subflags, e, GB(p1, 16, 8), &v)); break;
141  case VEH_ROAD: value.AddCost(CmdBuildRoadVehicle(tile, subflags, e, GB(p1, 16, 8), &v)); break;
142  case VEH_SHIP: value.AddCost(CmdBuildShip (tile, subflags, e, GB(p1, 16, 8), &v)); break;
143  case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft (tile, subflags, e, GB(p1, 16, 8), &v)); break;
144  default: NOT_REACHED(); // Safe due to IsDepotTile()
145  }
146 
147  if (value.Succeeded()) {
148  if (subflags & DC_EXEC) {
149  v->unitnumber = unit_num;
150  v->value = value.GetCost();
151  }
152 
153  if (refitting) {
154  /* Refit only one vehicle. If we purchased an engine, it may have gained free wagons. */
155  value.AddCost(CmdRefitVehicle(tile, flags, v->index, cargo | (1 << 16), nullptr));
156  } else {
157  /* Fill in non-refitted capacities */
159  }
160 
161  if (flags & DC_EXEC) {
165  if (IsLocalCompany()) {
166  InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
167  }
168  }
169 
170  if (subflags & DC_EXEC) {
173 
174  if (v->IsPrimaryVehicle()) {
176  if (!(subflags & DC_AUTOREPLACE)) OrderBackup::Restore(v, p2);
177  }
178  }
179 
180 
181  /* If we are not in DC_EXEC undo everything */
182  if (flags != subflags) {
183  DoCommand(0, v->index, 0, DC_EXEC, GetCmdSellVeh(v));
184  }
185  }
186 
187  /* Only restore if we actually did some refitting */
188  if (flags != subflags) RestoreRandomSeeds(saved_seeds);
189 
190  return value;
191 }
192 
193 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user);
194 
207 CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
208 {
209  Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
210  if (v == nullptr) return CMD_ERROR;
211 
212  Vehicle *front = v->First();
213 
214  CommandCost ret = CheckOwnership(front->owner);
215  if (ret.Failed()) return ret;
216 
217  if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
218 
219  if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
220 
221  /* Can we actually make the order backup, i.e. are there enough orders? */
222  if (p1 & MAKE_ORDER_BACKUP_FLAG &&
223  front->orders.list != nullptr &&
224  !front->orders.list->IsShared() &&
226  /* Only happens in exceptional cases when there aren't enough orders anyhow.
227  * Thus it should be safe to just drop the orders in that case. */
228  p1 &= ~MAKE_ORDER_BACKUP_FLAG;
229  }
230 
231  if (v->type == VEH_TRAIN) {
232  ret = CmdSellRailWagon(flags, v, GB(p1, 20, 12), p2);
233  } else {
234  ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
235 
236  if (flags & DC_EXEC) {
237  if (front->IsPrimaryVehicle() && p1 & MAKE_ORDER_BACKUP_FLAG) OrderBackup::Backup(front, p2);
238  delete front;
239  }
240  }
241 
242  return ret;
243 }
244 
254 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
255 {
256  /* Prepare callback param with info about the new cargo type. */
257  const Engine *e = Engine::Get(engine_type);
258 
259  /* Is this vehicle a NewGRF vehicle? */
260  if (e->GetGRF() != nullptr) {
261  const CargoSpec *cs = CargoSpec::Get(new_cid);
262  uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
263 
264  uint16 cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
265  if (cb_res != CALLBACK_FAILED) {
266  *auto_refit_allowed = HasBit(cb_res, 14);
267  int factor = GB(cb_res, 0, 14);
268  if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
269  return factor;
270  }
271  }
272 
273  *auto_refit_allowed = e->info.refit_cost == 0;
274  return (v == nullptr || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
275 }
276 
286 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
287 {
288  ExpensesType expense_type;
289  const Engine *e = Engine::Get(engine_type);
290  Price base_price;
291  int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
292  switch (e->type) {
293  case VEH_SHIP:
294  base_price = PR_BUILD_VEHICLE_SHIP;
295  expense_type = EXPENSES_SHIP_RUN;
296  break;
297 
298  case VEH_ROAD:
299  base_price = PR_BUILD_VEHICLE_ROAD;
300  expense_type = EXPENSES_ROADVEH_RUN;
301  break;
302 
303  case VEH_AIRCRAFT:
304  base_price = PR_BUILD_VEHICLE_AIRCRAFT;
305  expense_type = EXPENSES_AIRCRAFT_RUN;
306  break;
307 
308  case VEH_TRAIN:
309  base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
310  cost_factor <<= 1;
311  expense_type = EXPENSES_TRAIN_RUN;
312  break;
313 
314  default: NOT_REACHED();
315  }
316  if (cost_factor < 0) {
317  return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
318  } else {
319  return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
320  }
321 }
322 
324 struct RefitResult {
326  uint capacity;
328  byte subtype;
329 };
330 
343 static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
344 {
345  CommandCost cost(v->GetExpenseType(false));
346  uint total_capacity = 0;
347  uint total_mail_capacity = 0;
348  num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
349 
350  VehicleSet vehicles_to_refit;
351  if (!only_this) {
352  GetVehicleSet(vehicles_to_refit, v, num_vehicles);
353  /* In this case, we need to check the whole chain. */
354  v = v->First();
355  }
356 
357  std::vector<RefitResult> refit_result;
358 
360  byte actual_subtype = new_subtype;
361  for (; v != nullptr; v = (only_this ? nullptr : v->Next())) {
362  /* Reset actual_subtype for every new vehicle */
363  if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
364 
365  if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end() && !only_this) continue;
366 
367  const Engine *e = v->GetEngine();
368  if (!e->CanCarryCargo()) continue;
369 
370  /* If the vehicle is not refittable, or does not allow automatic refitting,
371  * count its capacity nevertheless if the cargo matches */
372  bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
373  if (!refittable && v->cargo_type != new_cid) continue;
374 
375  /* Determine best fitting subtype if requested */
376  if (actual_subtype == 0xFF) {
377  actual_subtype = GetBestFittingSubType(v, v, new_cid);
378  }
379 
380  /* Back up the vehicle's cargo type */
381  CargoID temp_cid = v->cargo_type;
382  byte temp_subtype = v->cargo_subtype;
383  if (refittable) {
384  v->cargo_type = new_cid;
385  v->cargo_subtype = actual_subtype;
386  }
387 
388  uint16 mail_capacity = 0;
389  uint amount = e->DetermineCapacity(v, &mail_capacity);
390  total_capacity += amount;
391  /* mail_capacity will always be zero if the vehicle is not an aircraft. */
392  total_mail_capacity += mail_capacity;
393 
394  if (!refittable) continue;
395 
396  /* Restore the original cargo type */
397  v->cargo_type = temp_cid;
398  v->cargo_subtype = temp_subtype;
399 
400  bool auto_refit_allowed;
401  CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, actual_subtype, &auto_refit_allowed);
402  if (auto_refit && (flags & DC_QUERY_COST) == 0 && !auto_refit_allowed) {
403  /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total.
404  * When querrying cost/capacity (for example in order refit GUI), we always assume 'allowed'.
405  * It is not predictable. */
406  total_capacity -= amount;
407  total_mail_capacity -= mail_capacity;
408 
409  if (v->cargo_type == new_cid) {
410  /* Add the old capacity nevertheless, if the cargo matches */
411  total_capacity += v->cargo_cap;
412  if (v->type == VEH_AIRCRAFT) total_mail_capacity += v->Next()->cargo_cap;
413  }
414  continue;
415  }
416  cost.AddCost(refit_cost);
417 
418  /* Record the refitting.
419  * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
420  * (weird NewGRFs)
421  * Note:
422  * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
423  * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
424  * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
425  * autorefit to behave the same, and we need its result for auto_refit_allowed.
426  */
427  refit_result.push_back({v, amount, mail_capacity, actual_subtype});
428  }
429 
430  if (flags & DC_EXEC) {
431  /* Store the result */
432  for (RefitResult &result : refit_result) {
433  Vehicle *u = result.v;
434  u->refit_cap = (u->cargo_type == new_cid) ? min(result.capacity, u->refit_cap) : 0;
435  if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
436  u->cargo_type = new_cid;
437  u->cargo_cap = result.capacity;
438  u->cargo_subtype = result.subtype;
439  if (u->type == VEH_AIRCRAFT) {
440  Vehicle *w = u->Next();
441  w->refit_cap = min(w->refit_cap, result.mail_capacity);
442  w->cargo_cap = result.mail_capacity;
443  if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
444  }
445  }
446  }
447 
448  refit_result.clear();
449  _returned_refit_capacity = total_capacity;
450  _returned_mail_refit_capacity = total_mail_capacity;
451  return cost;
452 }
453 
469 CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
470 {
471  Vehicle *v = Vehicle::GetIfValid(p1);
472  if (v == nullptr) return CMD_ERROR;
473 
474  /* Don't allow disasters and sparks and such to be refitted.
475  * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
477 
478  Vehicle *front = v->First();
479 
480  CommandCost ret = CheckOwnership(front->owner);
481  if (ret.Failed()) return ret;
482 
483  bool auto_refit = HasBit(p2, 24);
484  bool free_wagon = v->type == VEH_TRAIN && Train::From(front)->IsFreeWagon(); // used by autoreplace/renew
485 
486  /* Don't allow shadows and such to be refitted. */
487  if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return CMD_ERROR;
488 
489  /* Allow auto-refitting only during loading and normal refitting only in a depot. */
490  if ((flags & DC_QUERY_COST) == 0 && // used by the refit GUI, including the order refit GUI.
491  !free_wagon && // used by autoreplace/renew
492  (!auto_refit || !front->current_order.IsType(OT_LOADING)) && // refit inside stations
493  !front->IsStoppedInDepot()) { // refit inside depots
494  return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
495  }
496 
497  if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
498 
499  /* Check cargo */
500  CargoID new_cid = GB(p2, 0, 8);
501  byte new_subtype = GB(p2, 8, 8);
502  if (new_cid >= NUM_CARGO) return CMD_ERROR;
503 
504  /* For ships and aircraft there is always only one. */
505  bool only_this = HasBit(p2, 25) || front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
506  uint8 num_vehicles = GB(p2, 16, 8);
507 
508  CommandCost cost = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
509 
510  if (flags & DC_EXEC) {
511  /* Update the cached variables */
512  switch (v->type) {
513  case VEH_TRAIN:
514  Train::From(front)->ConsistChanged(auto_refit ? CCF_AUTOREFIT : CCF_REFIT);
515  break;
516  case VEH_ROAD:
517  RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
519  break;
520 
521  case VEH_SHIP:
523  Ship::From(v)->UpdateCache();
524  break;
525 
526  case VEH_AIRCRAFT:
529  break;
530 
531  default: NOT_REACHED();
532  }
533  front->MarkDirty();
534 
535  if (!free_wagon) {
538  }
540  } else {
541  /* Always invalidate the cache; querycost might have filled it. */
543  }
544 
545  return cost;
546 }
547 
557 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
558 {
559  /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
560  if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
561 
562  Vehicle *v = Vehicle::GetIfValid(p1);
563  if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
564 
565  CommandCost ret = CheckOwnership(v->owner);
566  if (ret.Failed()) return ret;
567 
568  if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
569 
570  switch (v->type) {
571  case VEH_TRAIN:
572  if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER);
573  break;
574 
575  case VEH_SHIP:
576  case VEH_ROAD:
577  break;
578 
579  case VEH_AIRCRAFT: {
580  Aircraft *a = Aircraft::From(v);
581  /* cannot stop airplane when in flight, or when taking off / landing */
582  if (a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
583  if (HasBit(a->flags, VAF_HELI_DIRECT_DESCENT)) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
584  break;
585  }
586 
587  default: return CMD_ERROR;
588  }
589 
590  if (HasBit(p2, 0)) {
591  /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
592  uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
593  StringID error = STR_NULL;
594  if (callback != CALLBACK_FAILED) {
595  if (v->GetGRF()->grf_version < 8) {
596  /* 8 bit result 0xFF means 'allow' */
597  if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
598  } else {
599  if (callback < 0x400) {
600  error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
601  } else {
602  switch (callback) {
603  case 0x400: // allow
604  break;
605 
606  default: // unknown reason -> disallow
607  error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
608  break;
609  }
610  }
611  }
612  }
613  if (error != STR_NULL) return_cmd_error(error);
614  }
615 
616  if (flags & DC_EXEC) {
617  if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, STR_NEWS_TRAIN_IS_WAITING + v->type);
618 
619  v->vehstatus ^= VS_STOPPED;
620  if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
621  v->MarkDirty();
626  }
627  return CommandCost();
628 }
629 
641 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
642 {
643  VehicleList list;
644  bool do_start = HasBit(p1, 0);
645  bool vehicle_list_window = HasBit(p1, 1);
646 
648  if (!vli.UnpackIfValid(p2)) return CMD_ERROR;
650 
651  if (vehicle_list_window) {
652  if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
653  } else {
654  /* Get the list of vehicles in the depot */
655  BuildDepotVehicleList(vli.vtype, tile, &list, nullptr);
656  }
657 
658  for (uint i = 0; i < list.size(); i++) {
659  const Vehicle *v = list[i];
660 
661  if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
662 
663  if (!vehicle_list_window && !v->IsChainInDepot()) continue;
664 
665  /* Just try and don't care if some vehicle's can't be stopped. */
666  DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
667  }
668 
669  return CommandCost();
670 }
671 
681 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
682 {
683  VehicleList list;
684 
686  VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
687 
688  if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
689 
690  uint sell_command = GetCmdSellVeh(vehicle_type);
691 
692  /* Get the list of vehicles in the depot */
693  BuildDepotVehicleList(vehicle_type, tile, &list, &list);
694 
695  CommandCost last_error = CMD_ERROR;
696  bool had_success = false;
697  for (uint i = 0; i < list.size(); i++) {
698  CommandCost ret = DoCommand(tile, list[i]->index | (1 << 20), 0, flags, sell_command);
699  if (ret.Succeeded()) {
700  cost.AddCost(ret);
701  had_success = true;
702  } else {
703  last_error = ret;
704  }
705  }
706 
707  return had_success ? cost : last_error;
708 }
709 
719 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
720 {
721  VehicleList list;
723  VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
724 
725  if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
726  if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
727 
728  /* Get the list of vehicles in the depot */
729  BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
730 
731  for (uint i = 0; i < list.size(); i++) {
732  const Vehicle *v = list[i];
733 
734  /* Ensure that the vehicle completely in the depot */
735  if (!v->IsChainInDepot()) continue;
736 
737  CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
738 
739  if (ret.Succeeded()) cost.AddCost(ret);
740  }
741  return cost;
742 }
743 
749 static bool IsUniqueVehicleName(const char *name)
750 {
751  for (const Vehicle *v : Vehicle::Iterate()) {
752  if (v->name != nullptr && strcmp(v->name, name) == 0) return false;
753  }
754 
755  return true;
756 }
757 
763 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
764 {
765  char buf[256];
766 
767  /* Find the position of the first digit in the last group of digits. */
768  size_t number_position;
769  for (number_position = strlen(src->name); number_position > 0; number_position--) {
770  /* The design of UTF-8 lets this work simply without having to check
771  * for UTF-8 sequences. */
772  if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
773  }
774 
775  /* Format buffer and determine starting number. */
776  int num;
777  byte padding = 0;
778  if (number_position == strlen(src->name)) {
779  /* No digit at the end, so start at number 2. */
780  strecpy(buf, src->name, lastof(buf));
781  strecat(buf, " ", lastof(buf));
782  number_position = strlen(buf);
783  num = 2;
784  } else {
785  /* Found digits, parse them and start at the next number. */
786  strecpy(buf, src->name, lastof(buf));
787  buf[number_position] = '\0';
788  char *endptr;
789  num = strtol(&src->name[number_position], &endptr, 10) + 1;
790  padding = endptr - &src->name[number_position];
791  }
792 
793  /* Check if this name is already taken. */
794  for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
795  /* Attach the number to the temporary name. */
796  seprintf(&buf[number_position], lastof(buf), "%0*d", padding, num);
797 
798  /* Check the name is unique. */
799  if (IsUniqueVehicleName(buf)) {
800  dst->name = stredup(buf);
801  break;
802  }
803  }
804 
805  /* All done. If we didn't find a name, it'll just use its default. */
806 }
807 
817 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
818 {
820 
821  Vehicle *v = Vehicle::GetIfValid(p1);
822  if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
823  Vehicle *v_front = v;
824  Vehicle *w = nullptr;
825  Vehicle *w_front = nullptr;
826  Vehicle *w_rear = nullptr;
827 
828  /*
829  * v_front is the front engine in the original vehicle
830  * v is the car/vehicle of the original vehicle that is currently being copied
831  * w_front is the front engine of the cloned vehicle
832  * w is the car/vehicle currently being cloned
833  * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
834  */
835 
836  CommandCost ret = CheckOwnership(v->owner);
837  if (ret.Failed()) return ret;
838 
839  if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return CMD_ERROR;
840 
841  /* check that we can allocate enough vehicles */
842  if (!(flags & DC_EXEC)) {
843  int veh_counter = 0;
844  do {
845  veh_counter++;
846  } while ((v = v->Next()) != nullptr);
847 
848  if (!Vehicle::CanAllocateItem(veh_counter)) {
849  return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
850  }
851  }
852 
853  v = v_front;
854 
855  do {
856  if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
857  /* we build the rear ends of multiheaded trains with the front ones */
858  continue;
859  }
860 
861  /* In case we're building a multi headed vehicle and the maximum number of
862  * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
863  * be cloned. When the non-primary engines were build they were seen as
864  * 'new' vehicles whereas they would immediately be joined with a primary
865  * engine. This caused the vehicle to be not build as 'the limit' had been
866  * reached, resulting in partially build vehicles and such. */
867  DoCommandFlag build_flags = flags;
868  if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
869 
870  CommandCost cost = DoCommand(tile, v->engine_type | (1 << 16) | (CT_INVALID << 24), 0, build_flags, GetCmdBuildVeh(v));
871 
872  if (cost.Failed()) {
873  /* Can't build a part, then sell the stuff we already made; clear up the mess */
874  if (w_front != nullptr) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
875  return cost;
876  }
877 
878  total_cost.AddCost(cost);
879 
880  if (flags & DC_EXEC) {
881  w = Vehicle::Get(_new_vehicle_id);
882 
883  if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
885  }
886 
887  if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
888  /* this s a train car
889  * add this unit to the end of the train */
890  CommandCost result = DoCommand(0, w->index | 1 << 20, w_rear->index, flags, CMD_MOVE_RAIL_VEHICLE);
891  if (result.Failed()) {
892  /* The train can't be joined to make the same consist as the original.
893  * Sell what we already made (clean up) and return an error. */
894  DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
895  DoCommand(w_front->tile, w->index | 1 << 20, 0, flags, GetCmdSellVeh(w));
896  return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
897  }
898  } else {
899  /* this is a front engine or not a train. */
900  w_front = w;
902  w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
903  w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
904  }
905  w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
906  }
907  } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
908 
909  if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
910  /* for trains this needs to be the front engine due to the callback function */
911  _new_vehicle_id = w_front->index;
912  }
913 
914  if (flags & DC_EXEC) {
915  /* Cloned vehicles belong to the same group */
916  DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
917  }
918 
919 
920  /* Take care of refitting. */
921  w = w_front;
922  v = v_front;
923 
924  /* Both building and refitting are influenced by newgrf callbacks, which
925  * makes it impossible to accurately estimate the cloning costs. In
926  * particular, it is possible for engines of the same type to be built with
927  * different numbers of articulated parts, so when refitting we have to
928  * loop over real vehicles first, and then the articulated parts of those
929  * vehicles in a different loop. */
930  do {
931  do {
932  if (flags & DC_EXEC) {
933  assert(w != nullptr);
934 
935  /* Find out what's the best sub type */
936  byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
937  if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
938  CommandCost cost = DoCommand(0, w->index, v->cargo_type | 1U << 25 | (subtype << 8), flags, GetCmdRefitVeh(v));
939  if (cost.Succeeded()) total_cost.AddCost(cost);
940  }
941 
942  if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
943  w = w->GetNextArticulatedPart();
944  } else {
945  break;
946  }
947  } else {
948  const Engine *e = v->GetEngine();
949  CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
950 
951  if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
952  bool dummy;
953  total_cost.AddCost(GetRefitCost(nullptr, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
954  }
955  }
956 
957  if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
958  v = v->GetNextArticulatedPart();
959  } else {
960  break;
961  }
962  } while (v != nullptr);
963 
964  if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
965  } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
966 
967  if (flags & DC_EXEC) {
968  /*
969  * Set the orders of the vehicle. Cannot do it earlier as we need
970  * the vehicle refitted before doing this, otherwise the moved
971  * cargo types might not match (passenger vs non-passenger)
972  */
973  DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER);
974 
975  /* Now clone the vehicle's name, if it has one. */
976  if (v_front->name != nullptr) CloneVehicleName(v_front, w_front);
977  }
978 
979  /* Since we can't estimate the cost of cloning a vehicle accurately we must
980  * check whether the company has enough money manually. */
981  if (!CheckCompanyHasMoney(total_cost)) {
982  if (flags & DC_EXEC) {
983  /* The vehicle has already been bought, so now it must be sold again. */
984  DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
985  }
986  return total_cost;
987  }
988 
989  return total_cost;
990 }
991 
1000 {
1001  VehicleList list;
1002 
1003  if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
1004 
1005  /* Send all the vehicles to a depot */
1006  bool had_success = false;
1007  for (uint i = 0; i < list.size(); i++) {
1008  const Vehicle *v = list[i];
1009  CommandCost ret = DoCommand(v->tile, v->index | (service ? DEPOT_SERVICE : 0U) | DEPOT_DONT_CANCEL, 0, flags, GetCmdSendToDepot(vli.vtype));
1010 
1011  if (ret.Succeeded()) {
1012  had_success = true;
1013 
1014  /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
1015  * In this case we know that at least one vehicle can be sent to a depot
1016  * and we will issue the command. We can now safely quit the loop, knowing
1017  * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
1018  if (!(flags & DC_EXEC)) break;
1019  }
1020  }
1021 
1022  return had_success ? CommandCost() : CMD_ERROR;
1023 }
1024 
1036 CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1037 {
1038  if (p1 & DEPOT_MASS_SEND) {
1039  /* Mass goto depot requested */
1041  if (!vli.UnpackIfValid(p2)) return CMD_ERROR;
1042  return SendAllVehiclesToDepot(flags, (p1 & DEPOT_SERVICE) != 0, vli);
1043  }
1044 
1045  Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
1046  if (v == nullptr) return CMD_ERROR;
1047  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
1048 
1049  return v->SendToDepot(flags, (DepotCommand)(p1 & DEPOT_COMMAND_MASK));
1050 }
1051 
1061 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1062 {
1063  Vehicle *v = Vehicle::GetIfValid(p1);
1064  if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1065 
1066  CommandCost ret = CheckOwnership(v->owner);
1067  if (ret.Failed()) return ret;
1068 
1069  bool reset = StrEmpty(text);
1070 
1071  if (!reset) {
1073  if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1074  }
1075 
1076  if (flags & DC_EXEC) {
1077  free(v->name);
1078  v->name = reset ? nullptr : stredup(text);
1081  }
1082 
1083  return CommandCost();
1084 }
1085 
1086 
1099 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1100 {
1101  Vehicle *v = Vehicle::GetIfValid(p1);
1102  if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1103 
1104  CommandCost ret = CheckOwnership(v->owner);
1105  if (ret.Failed()) return ret;
1106 
1107  const Company *company = Company::Get(v->owner);
1108  bool iscustom = HasBit(p2, 16);
1109  bool ispercent = iscustom ? HasBit(p2, 17) : company->settings.vehicle.servint_ispercent;
1110 
1111  uint16 serv_int;
1112  if (iscustom) {
1113  serv_int = GB(p2, 0, 16);
1114  if (serv_int != GetServiceIntervalClamped(serv_int, ispercent)) return CMD_ERROR;
1115  } else {
1116  serv_int = CompanyServiceInterval(company, v->type);
1117  }
1118 
1119  if (flags & DC_EXEC) {
1120  v->SetServiceInterval(serv_int);
1121  v->SetServiceIntervalIsCustom(iscustom);
1122  v->SetServiceIntervalIsPercent(ispercent);
1124  }
1125 
1126  return CommandCost();
1127 }
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition: engine.cpp:1123
Road vehicle states.
CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v)
Build a ship.
Definition: ship_cmd.cpp:825
VehicleSettings vehicle
options for vehicles
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:43
Vehicle is stopped by the player.
Definition: vehicle_base.h:31
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:307
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
Definition of stuff that is very close to a company, like the company struct itself.
CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Build a vehicle.
Definition: vehicle_cmd.cpp:87
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:340
Money value
Value of the vehicle.
Definition: vehicle_base.h:239
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: vehicle_base.h:362
The information about a vehicle list.
Definition: vehiclelist.h:29
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3218
static char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: depend.cpp:97
Functions related to the autoreplace GUIs.
uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
Clamp the service interval to the correct min/max.
Definition: order_cmd.cpp:1928
Don&#39;t cancel current goto depot command if any.
Definition: vehicle_type.h:68
Functions and type for generating vehicle lists.
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user)
Sell a (single) train wagon/engine.
Definition: train_cmd.cpp:1343
Train vehicle type.
Definition: vehicle_type.h:24
union Vehicle::@49 orders
The orders currently assigned to the vehicle.
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:329
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:171
Conventional Take Off and Landing, i.e. planes.
Definition: engine_type.h:92
Vehicle * v
Vehicle to refit.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:407
Helper structure for RefitVehicle()
Base for the train class.
Stores the state of all random number generators.
Definition: random_func.hpp:33
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
uint16 cur_speed
current speed
Definition: vehicle_base.h:291
query cost only, don&#39;t build.
Definition: command_type.h:348
uint Truncate(uint max_move=UINT_MAX)
Truncates the cargo in this list to the given amount.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:23
Ship vehicle type.
Definition: vehicle_type.h:26
Depot view; Window numbers:
Definition: window_type.h:344
Base class for groups and group functions.
Maximal number of cargo types in a game.
Definition: cargo_type.h:64
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition: vehicle_base.h:514
bool CheckCompanyHasMoney(CommandCost &cost)
Verify whether the company can pay the bill.
Specification of a cargo type.
Definition: cargotype.h:55
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
OrderList * list
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:319
static void RestoreRandomSeeds(const SavedRandomSeeds &storage)
Restores previously saved seeds.
Definition: random_func.hpp:52
byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
Get the best fitting subtype when &#39;cloning&#39;/&#39;replacing&#39; v_from with v_for.
Functions related to vehicles.
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition: aircraft.h:74
CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Sells all vehicles in a depot.
Called when the company (or AI) tries to start or stop a vehicle.
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:65
Vehicle data structure.
Definition: vehicle_base.h:210
bool UnpackIfValid(uint32 data)
Unpack a VehicleListIdentifier from a single uint32.
Definition: vehiclelist.cpp:38
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.
Start or stop this vehicle, and show information about the current state.
Tindex index
Index of this pool item.
Definition: pool_type.hpp:227
uint TotalCount() const
Returns sum of cargo, including reserved cargo.
Definition: cargopacket.h:360
Helper functions to extract data from command parameters.
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
bool GenerateVehicleSortList(VehicleList *list, const VehicleListIdentifier &vli)
Generate a list of vehicles based on window type.
Base for aircraft.
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
clone (and share) an order
Definition: command_type.h:272
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
Common return value for all commands.
Definition: command_type.h:23
uint32 cached_power
Total power of the consist (valid only for the first engine).
CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Starts or stops a lot of vehicles.
uint16 classes
Classes of this cargo type.
Definition: cargotype.h:78
byte vehstatus
Status.
Definition: vehicle_base.h:315
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Definition: vehicle.cpp:1725
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
CompanySettings settings
settings specific for each company
Definition: company_base.h:127
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:741
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition: engine_base.h:79
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:942
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:62
CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Autoreplace all vehicles in the depot.
CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Give a custom name to your vehicle.
DepotCommand
Flags to add to p1 for goto depot commands.
Definition: vehicle_type.h:65
CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Clone a vehicle.
replace/renew a vehicle while it is in a depot
Definition: command_type.h:315
Pseudo random number generator.
start or stop a vehicle
Definition: command_type.h:313
Running costs aircraft.
Definition: economy_type.h:153
Invalid cargo type.
Definition: cargo_type.h:68
uint16 service_interval
The interval for (automatic) servicing; either in days or %.
Definition: base_consist.h:25
Called to determine the cost factor for refitting a vehicle.
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:3337
uint16 cargo_cap
total capacity
Definition: vehicle_base.h:305
Various declarations for airports.
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
Header of Action 04 "universal holder" structure and functions.
Map related accessors for depots.
static const uint32 MAKE_ORDER_BACKUP_FLAG
Flag to pass to the vehicle construction command when an order should be preserved.
Definition: order_backup.h:29
Functions related to low-level strings.
Vehicle is crashed.
Definition: vehicle_base.h:37
void UpdateCache()
Update the caches of this ship.
Definition: ship_cmd.cpp:202
Money GetCost() const
Return how much a new engine costs.
Definition: engine.cpp:319
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:431
static const uint MAX_LENGTH_VEHICLE_NAME_CHARS
The maximum length of a vehicle name in characters including &#39;\0&#39;.
Definition: vehicle_type.h:73
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:289
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:445
byte cargo_subtype
Used for livery refits (NewGRF variations)
Definition: vehicle_base.h:304
byte subtype
Type of aircraft.
Definition: engine_type.h:101
uint16 crash_anim_pos
Crash animation counter.
Definition: train.h:91
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
void DeleteVehicleNews(VehicleID vid, StringID news)
Delete a news item type about a vehicle.
Definition: news_gui.cpp:903
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:106
VehicleDefaultSettings vehicle
default settings for vehicles
Functions related to engines.
Heading for terminal 7.
Definition: airport.h:80
refit the cargo space of a vehicle
Definition: command_type.h:216
byte subtype
cargo subtype to refit to
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:61
DoCommandFlag
List of flags for a command.
Definition: command_type.h:344
simple wagon, not motorized
Definition: engine_type.h:29
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:150
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 of base types and functions in a cross-platform compatible way.
virtual ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
Definition: vehicle_base.h:421
Tells that it&#39;s a mass send to depot command (type in VLW flag)
Definition: vehicle_type.h:67
build a vehicle
Definition: command_type.h:214
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:890
A number of safeguards to prevent using unsafe methods.
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle) ...
Definition: vehicle_base.h:458
Vehicle * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
Definition: vehicle_base.h:952
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:40
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:303
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:136
Vehicle view; Window numbers:
Definition: window_type.h:332
static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
Refits a vehicle (chain).
Functions related to order backups.
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:881
bool IsShared() const
Is this a shared order list?
Definition: order_base.h:331
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:142
TileIndex tile
Current tile index.
Definition: vehicle_base.h:228
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Valid changes for autorefitting in stations.
Definition: train.h:50
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
Definition: group_cmd.cpp:133
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Definition: vehicle_base.h:899
uint capacity
New capacity of vehicle.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:271
uint8 cargo_map[NUM_CARGO]
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:127
Airplane has arrived at a runway for take-off.
Definition: airport.h:72
static VehicleType GetDepotVehicleType(TileIndex t)
Get the type of vehicles that can use a depot.
Definition: depot_map.h:65
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
uint16 refit_cap
Capacity left over from before last refit.
Definition: vehicle_base.h:306
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:592
bool Failed() const
Did this command fail?
Definition: command_type.h:159
static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
Send all vehicles of type to depots.
CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v)
Build a road vehicle.
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:33
byte state
State of the airport.
Definition: aircraft.h:79
autoreplace/autorenew is in progress, this shall disable vehicle limits when building, and ignore certain restrictions when undoing things (like vehicle attach callback)
Definition: command_type.h:353
CommandCost CmdBuildAircraft(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v)
Build an aircraft.
uint CountArticulatedParts(EngineID engine_type, bool purchase_window)
Count the number of articulated parts of an engine.
char * name
Name of vehicle.
Definition: base_consist.h:18
execute the given command
Definition: command_type.h:346
The vehicle will leave the depot right after arrival (service only)
Definition: vehicle_type.h:66
Functions related to companies.
Functions related to articulated vehicles.
add a vehicle to a group
Definition: command_type.h:322
Automatic refitting is allowed.
Definition: engine_type.h:158
The helicopter is descending directly at its destination (helipad or in front of hangar) ...
Definition: aircraft.h:47
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
Definition: vehicle_base.h:469
sell a vehicle
Definition: command_type.h:215
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:138
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:378
Running costs trains.
Definition: economy_type.h:151
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:3232
uint _returned_refit_capacity
Stores the capacity after a refit operation.
Definition: vehicle.cpp:85
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:57
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:310
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:117
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:78
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:579
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:2887
bool servint_ispercent
service intervals are in percents
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:113
indicates a combination of two locomotives
Definition: engine_type.h:28
Vehicle * GetNextArticulatedPart() const
Get the next part of an articulated engine.
Definition: vehicle_base.h:909
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:204
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:66
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
uint mail_capacity
New mail capacity of aircraft.
Reverse the visible direction of the vehicle.
Definition: train.h:28
uint16 _returned_mail_refit_capacity
Stores the mail capacity after a refit operation (Aircraft only).
Definition: vehicle.cpp:86
uint GetDisplayDefaultCapacity(uint16 *mail_capacity=nullptr) const
Determines the default cargo capacity of an engine for display purposes.
Definition: engine_base.h:99
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:299
Vehicle details; Window numbers:
Definition: window_type.h:193
Functions related to commands.
CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Send a vehicle to the depot.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:45
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
Definition: group_cmd.cpp:156
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:761
uint16 UnitID
Type for the company global vehicle unit number.
Base for ships.
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:91
CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Refits a vehicle to the specified cargo type.
Running costs ships.
Definition: economy_type.h:154
CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command)
Send this vehicle to the depot using the given command(s).
Definition: vehicle.cpp:2305
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
Aircraft vehicle type.
Definition: vehicle_type.h:27
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:129
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
uint8 roadveh_acceleration_model
realistic acceleration for road vehicles
CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the service interval of a vehicle.
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:286
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
static void SaveRandomSeeds(SavedRandomSeeds *storage)
Saves the current seeds.
Definition: random_func.hpp:42
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:751
send a vehicle to a depot
Definition: command_type.h:217
#define CMD_MSG(x)
Used to combine a StringID with the command.
Definition: command_type.h:370
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
New vehicles.
Definition: economy_type.h:150
byte flags
Aircraft flags.
Definition: aircraft.h:83
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
Definition: vehicle_base.h:508
static bool IsDepotTile(TileIndex tile)
Is the given tile a tile with a depot on it?
Definition: depot_map.h:41
static void Restore(Vehicle *v, uint32 user)
Restore the data of this order to the given vehicle.
static void Backup(const Vehicle *v, uint32 user)
Create an order backup for the given vehicle.
int do_start
flag for starting playback of next_file at next opportunity
Definition: win32_m.cpp:37
std::vector< const Vehicle * > VehicleList
A list of vehicles.
Definition: vehiclelist.h:53
move a rail vehicle (in the depot)
Definition: command_type.h:220
Running costs road vehicles.
Definition: economy_type.h:152
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3246
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition: engine.cpp:204
Functions related to news.
Company view; Window numbers:
Definition: window_type.h:362
VehicleType vtype
The vehicle type associated with this list.
Definition: vehiclelist.h:31
ExpensesType
Types of expenses.
Definition: economy_type.h:148
static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
Clone the custom name of a vehicle, adding or incrementing a number.
CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Sell a vehicle.
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Definition: vehicle_func.h:89
Road vehicle type.
Definition: vehicle_type.h:25
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:316
VehicleOrderID GetNumOrders() const
Get number of orders in the order list.
Definition: order_base.h:312
GroupID group_id
Index of group Pool array.
Definition: vehicle_base.h:324
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:3319
Valid changes for refitting in a depot.
Definition: train.h:51
GroundVehicleCache gcache
Cache of often calculated values.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1600
static bool IsUniqueVehicleName(const char *name)
Test if a name is unique among vehicle names.
CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v)
Build a railroad vehicle.
Definition: train_cmd.cpp:714
CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Start/Stop a vehicle.
Base for the NewGRF implementation.