OpenTTD
engine.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 "company_func.h"
12 #include "command_func.h"
13 #include "news_func.h"
14 #include "aircraft.h"
15 #include "newgrf.h"
16 #include "newgrf_engine.h"
17 #include "strings_func.h"
18 #include "core/random_func.hpp"
19 #include "window_func.h"
20 #include "date_func.h"
21 #include "autoreplace_gui.h"
22 #include "string_func.h"
23 #include "ai/ai.hpp"
24 #include "core/pool_func.hpp"
25 #include "engine_gui.h"
26 #include "engine_func.h"
27 #include "engine_base.h"
28 #include "company_base.h"
29 #include "vehicle_func.h"
30 #include "articulated_vehicles.h"
31 #include "error.h"
32 
33 #include "table/strings.h"
34 #include "table/engines.h"
35 
36 #include "safeguards.h"
37 
38 EnginePool _engine_pool("Engine");
40 
41 EngineOverrideManager _engine_mngr;
42 
48 
50 const uint8 _engine_counts[4] = {
51  lengthof(_orig_rail_vehicle_info),
52  lengthof(_orig_road_vehicle_info),
53  lengthof(_orig_ship_vehicle_info),
54  lengthof(_orig_aircraft_vehicle_info),
55 };
56 
58 const uint8 _engine_offsets[4] = {
59  0,
60  lengthof(_orig_rail_vehicle_info),
61  lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
62  lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
63 };
64 
65 assert_compile(lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info) + lengthof(_orig_aircraft_vehicle_info) == lengthof(_orig_engine_info));
66 
68 
69 Engine::Engine() :
70  name(nullptr),
71  overrides_count(0),
72  overrides(nullptr)
73 {
74 }
75 
76 Engine::Engine(VehicleType type, EngineID base)
77 {
78  this->type = type;
79  this->grf_prop.local_id = base;
80  this->list_position = base;
82 
83  /* Check if this base engine is within the original engine data range */
84  if (base >= _engine_counts[type]) {
85  /* Set model life to maximum to make wagons available */
86  this->info.base_life = 0xFF;
87  /* Set road vehicle tractive effort to the default value */
88  if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
89  /* Aircraft must have CT_INVALID as default, as there is no property */
90  if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
91  /* Set visual effect to the default value */
92  switch (type) {
93  case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
94  case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
95  case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
96  default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
97  }
98  /* Set cargo aging period to the default value. */
100  return;
101  }
102 
103  /* Copy the original engine info for this slot */
104  this->info = _orig_engine_info[_engine_offsets[type] + base];
105 
106  /* Copy the original engine data for this slot */
107  switch (type) {
108  default: NOT_REACHED();
109 
110  case VEH_TRAIN:
111  this->u.rail = _orig_rail_vehicle_info[base];
112  this->original_image_index = this->u.rail.image_index;
113  this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
114 
115  /* Set the default model life of original wagons to "infinite" */
116  if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
117 
118  break;
119 
120  case VEH_ROAD:
121  this->u.road = _orig_road_vehicle_info[base];
122  this->original_image_index = this->u.road.image_index;
123  this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
124  break;
125 
126  case VEH_SHIP:
127  this->u.ship = _orig_ship_vehicle_info[base];
128  this->original_image_index = this->u.ship.image_index;
129  this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
130  break;
131 
132  case VEH_AIRCRAFT:
133  this->u.air = _orig_aircraft_vehicle_info[base];
134  this->original_image_index = this->u.air.image_index;
135  this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
136  break;
137  }
138 }
139 
140 Engine::~Engine()
141 {
142  UnloadWagonOverrides(this);
143  free(this->name);
144 }
145 
150 bool Engine::IsEnabled() const
151 {
152  return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
153 }
154 
160 uint32 Engine::GetGRFID() const
161 {
162  const GRFFile *file = this->GetGRF();
163  return file == nullptr ? 0 : file->grfid;
164 }
165 
172 {
173  /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
174  * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
175  * for livery selection etc.
176  * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
177  */
178  switch (this->type) {
179  case VEH_TRAIN:
180  if (this->u.rail.capacity == 0) return false;
181  break;
182 
183  case VEH_ROAD:
184  if (this->u.road.capacity == 0) return false;
185  break;
186 
187  case VEH_SHIP:
188  case VEH_AIRCRAFT:
189  break;
190 
191  default: NOT_REACHED();
192  }
193  return this->GetDefaultCargoType() != CT_INVALID;
194 }
195 
196 
204 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
205 {
206  assert(v == nullptr || this->index == v->engine_type);
207  if (mail_capacity != nullptr) *mail_capacity = 0;
208 
209  if (!this->CanCarryCargo()) return 0;
210 
211  bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
212  CargoID default_cargo = this->GetDefaultCargoType();
213  CargoID cargo_type = (v != nullptr) ? v->cargo_type : default_cargo;
214 
215  if (mail_capacity != nullptr && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
216  *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
217  }
218 
219  /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
221  (new_multipliers || default_cargo != cargo_type || (v != nullptr && v->cargo_subtype != 0))) {
222  uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
223  if (callback != CALLBACK_FAILED) return callback;
224  }
225 
226  /* Get capacity according to property resp. CB */
227  uint capacity;
228  uint extra_mail_cap = 0;
229  switch (this->type) {
230  case VEH_TRAIN:
231  capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
232 
233  /* In purchase list add the capacity of the second head. Always use the plain property for this. */
234  if (v == nullptr && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
235  break;
236 
237  case VEH_ROAD:
238  capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
239  break;
240 
241  case VEH_SHIP:
242  capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
243  break;
244 
245  case VEH_AIRCRAFT:
246  capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
247  if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
248  extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
249  }
250  if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
251  default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
252  break;
253 
254  default: NOT_REACHED();
255  }
256 
257  if (!new_multipliers) {
258  /* Use the passenger multiplier for mail as well */
259  capacity += extra_mail_cap;
260  extra_mail_cap = 0;
261  }
262 
263  /* Apply multipliers depending on cargo- and vehicletype. */
264  if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
265  uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
266  uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
267  capacity *= cargo_multiplier;
268  if (extra_mail_cap > 0) {
269  uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
270  capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
271  }
272  capacity = (capacity + default_multiplier / 2) / default_multiplier;
273  }
274 
275  return capacity;
276 }
277 
283 {
284  Price base_price;
285  uint cost_factor;
286  switch (this->type) {
287  case VEH_ROAD:
288  base_price = this->u.road.running_cost_class;
289  if (base_price == INVALID_PRICE) return 0;
290  cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
291  break;
292 
293  case VEH_TRAIN:
294  base_price = this->u.rail.running_cost_class;
295  if (base_price == INVALID_PRICE) return 0;
296  cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
297  break;
298 
299  case VEH_SHIP:
300  base_price = PR_RUNNING_SHIP;
301  cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
302  break;
303 
304  case VEH_AIRCRAFT:
305  base_price = PR_RUNNING_AIRCRAFT;
306  cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
307  break;
308 
309  default: NOT_REACHED();
310  }
311 
312  return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
313 }
314 
320 {
321  Price base_price;
322  uint cost_factor;
323  switch (this->type) {
324  case VEH_ROAD:
325  base_price = PR_BUILD_VEHICLE_ROAD;
326  cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
327  break;
328 
329  case VEH_TRAIN:
330  if (this->u.rail.railveh_type == RAILVEH_WAGON) {
331  base_price = PR_BUILD_VEHICLE_WAGON;
332  cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
333  } else {
334  base_price = PR_BUILD_VEHICLE_TRAIN;
335  cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
336  }
337  break;
338 
339  case VEH_SHIP:
340  base_price = PR_BUILD_VEHICLE_SHIP;
341  cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
342  break;
343 
344  case VEH_AIRCRAFT:
345  base_price = PR_BUILD_VEHICLE_AIRCRAFT;
346  cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
347  break;
348 
349  default: NOT_REACHED();
350  }
351 
352  return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
353 }
354 
360 {
361  switch (this->type) {
362  case VEH_TRAIN:
363  return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
364 
365  case VEH_ROAD: {
366  uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
367  return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
368  }
369 
370  case VEH_SHIP:
371  return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
372 
373  case VEH_AIRCRAFT: {
374  uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
375  if (max_speed != 0) {
376  return (max_speed * 128) / 10;
377  }
378  return this->u.air.max_speed;
379  }
380 
381  default: NOT_REACHED();
382  }
383 }
384 
391 uint Engine::GetPower() const
392 {
393  /* Only trains and road vehicles have 'power'. */
394  switch (this->type) {
395  case VEH_TRAIN:
396  return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
397  case VEH_ROAD:
398  return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
399 
400  default: NOT_REACHED();
401  }
402 }
403 
410 {
411  /* Only trains and road vehicles have 'weight'. */
412  switch (this->type) {
413  case VEH_TRAIN:
414  return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
415  case VEH_ROAD:
416  return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
417 
418  default: NOT_REACHED();
419  }
420 }
421 
428 {
429  /* Only trains and road vehicles have 'tractive effort'. */
430  switch (this->type) {
431  case VEH_TRAIN:
432  return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256 / 1000;
433  case VEH_ROAD:
434  return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256 / 1000;
435 
436  default: NOT_REACHED();
437  }
438 }
439 
445 {
446  /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
448 }
449 
454 uint16 Engine::GetRange() const
455 {
456  switch (this->type) {
457  case VEH_AIRCRAFT:
458  return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
459 
460  default: NOT_REACHED();
461  }
462 }
463 
469 {
470  switch (this->type) {
471  case VEH_AIRCRAFT:
472  switch (this->u.air.subtype) {
473  case AIR_HELI: return STR_LIVERY_HELICOPTER;
474  case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
475  case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
476  default: NOT_REACHED();
477  }
478 
479  default: NOT_REACHED();
480  }
481 }
482 
487 {
488  this->clear();
490  for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
491  /*C++17: EngineIDMapping &eid = */ this->emplace_back();
492  EngineIDMapping &eid = this->back();
493  eid.type = type;
494  eid.grfid = INVALID_GRFID;
495  eid.internal_id = internal_id;
496  eid.substitute_id = internal_id;
497  }
498  }
499 }
500 
510 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
511 {
512  EngineID index = 0;
513  for (const EngineIDMapping &eid : *this) {
514  if (eid.type == type && eid.grfid == grfid && eid.internal_id == grf_local_id) {
515  return index;
516  }
517  index++;
518  }
519  return INVALID_ENGINE;
520 }
521 
528 {
529  for (const Vehicle *v : Vehicle::Iterate()) {
530  if (IsCompanyBuildableVehicleType(v)) return false;
531  }
532 
533  /* Reset the engines, they will get new EngineIDs */
534  _engine_mngr.ResetToDefaultMapping();
536 
537  return true;
538 }
539 
544 {
546  _engine_pool.CleanPool();
547 
548  assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES);
549  uint index = 0;
550  for (const EngineIDMapping &eid : _engine_mngr) {
551  /* Assert is safe; there won't be more than 256 original vehicles
552  * in any case, and we just cleaned the pool. */
553  assert(Engine::CanAllocateItem());
554  const Engine *e = new Engine(eid.type, eid.internal_id);
555  assert(e->index == index);
556  index++;
557  }
558 }
559 
560 void ShowEnginePreviewWindow(EngineID engine);
561 
567 static bool IsWagon(EngineID index)
568 {
569  const Engine *e = Engine::Get(index);
570  return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
571 }
572 
578 {
579  uint age = e->age;
580 
581  /* Check for early retirement */
582  if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
583  int retire_early = e->info.retire_early;
584  uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
585  if (retire_early != 0 && age >= retire_early_max_age) {
586  /* Early retirement is enabled and we're past the date... */
587  e->company_avail = 0;
589  }
590  }
591 
592  if (age < e->duration_phase_1) {
593  uint start = e->reliability_start;
594  e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
595  } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
596  /* We are at the peak of this engines life. It will have max reliability.
597  * This is also true if the engines never expire. They will not go bad over time */
599  } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
600  uint max = e->reliability_max;
601  e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
602  } else {
603  /* time's up for this engine.
604  * We will now completely retire this design */
605  e->company_avail = 0;
607  /* Kick this engine out of the lists */
609  }
610  SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
612 }
613 
616 {
617  /* Determine last engine aging year, default to 2050 as previously. */
619 
620  for (const Engine *e : Engine::Iterate()) {
621  const EngineInfo *ei = &e->info;
622 
623  /* Exclude certain engines */
625  if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
626 
627  /* Base year ending date on half the model life */
628  YearMonthDay ymd;
629  ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
630 
632  }
633 }
634 
640 void StartupOneEngine(Engine *e, Date aging_date)
641 {
642  const EngineInfo *ei = &e->info;
643 
644  e->age = 0;
645  e->flags = 0;
646  e->company_avail = 0;
647  e->company_hidden = 0;
648 
649  /* Don't randomise the start-date in the first two years after gamestart to ensure availability
650  * of engines in early starting games.
651  * Note: TTDP uses fixed 1922 */
652  SavedRandomSeeds saved_seeds;
653  SaveRandomSeeds(&saved_seeds);
655  ei->base_intro ^
656  e->type ^
657  e->GetGRFID());
658  uint32 r = Random();
659 
661  if (e->intro_date <= _date) {
662  e->age = (aging_date - e->intro_date) >> 5;
663  e->company_avail = (CompanyMask)-1;
664  e->flags |= ENGINE_AVAILABLE;
665  }
666 
667  e->reliability_start = GB(r, 16, 14) + 0x7AE0;
668  r = Random();
669  e->reliability_max = GB(r, 0, 14) + 0xBFFF;
670  e->reliability_final = GB(r, 16, 14) + 0x3FFF;
671 
672  r = Random();
673  e->duration_phase_1 = GB(r, 0, 5) + 7;
674  e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
675  e->duration_phase_3 = GB(r, 9, 7) + 120;
676 
677  e->reliability_spd_dec = ei->decay_speed << 2;
678 
679  RestoreRandomSeeds(saved_seeds);
681 
682  /* prevent certain engines from ever appearing. */
684  e->flags |= ENGINE_AVAILABLE;
685  e->company_avail = 0;
686  }
687 }
688 
694 {
695  /* Aging of vehicles stops, so account for that when starting late */
696  const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
697 
698  for (Engine *e : Engine::Iterate()) {
699  StartupOneEngine(e, aging_date);
700  }
701 
702  /* Update the bitmasks for the vehicle lists */
703  for (Company *c : Company::Iterate()) {
704  c->avail_railtypes = GetCompanyRailtypes(c->index);
705  c->avail_roadtypes = GetCompanyRoadTypes(c->index);
706  }
707 
708  /* Invalidate any open purchase lists */
710 }
711 
717 static void AcceptEnginePreview(EngineID eid, CompanyID company)
718 {
719  Engine *e = Engine::Get(eid);
720  Company *c = Company::Get(company);
721 
722  SetBit(e->company_avail, company);
723  if (e->type == VEH_TRAIN) {
724  assert(e->u.rail.railtype < RAILTYPE_END);
726  } else if (e->type == VEH_ROAD) {
727  assert(e->u.road.roadtype < ROADTYPE_END);
729  }
730 
732  e->preview_asked = (CompanyMask)-1;
733  if (company == _local_company) {
735  }
736 
737  /* Update the toolbar. */
740 
741  /* Notify preview window, that it might want to close.
742  * Note: We cannot directly close the window.
743  * In singleplayer this function is called from the preview window, so
744  * we have to use the GUI-scope scheduling of InvalidateWindowData.
745  */
747 }
748 
755 {
756  CompanyID best_company = INVALID_COMPANY;
757 
758  /* For trains the cargomask has no useful meaning, since you can attach other wagons */
759  CargoTypes cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : ALL_CARGOTYPES;
760 
761  int32 best_hist = -1;
762  for (const Company *c : Company::Iterate()) {
763  if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
764  c->old_economy[0].performance_history > best_hist) {
765 
766  /* Check whether the company uses similar vehicles */
767  for (const Vehicle *v : Vehicle::Iterate()) {
768  if (v->owner != c->index || v->type != e->type) continue;
769  if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
770 
771  best_hist = c->old_economy[0].performance_history;
772  best_company = c->index;
773  break;
774  }
775  }
776  }
777 
778  return best_company;
779 }
780 
789 {
790  switch (type) {
795 
796  default: NOT_REACHED();
797  }
798 }
799 
802 {
803  for (Company *c : Company::Iterate()) {
804  c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
805  c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes, _date);
806  }
807 
808  if (_cur_year >= _year_engine_aging_stops) return;
809 
810  for (Engine *e : Engine::Iterate()) {
811  EngineID i = e->index;
812  if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
813  if (e->preview_company != INVALID_COMPANY) {
814  if (!--e->preview_wait) {
816  e->preview_company = INVALID_COMPANY;
817  }
818  } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
819  e->preview_company = GetPreviewCompany(e);
820 
821  if (e->preview_company == INVALID_COMPANY) {
822  e->preview_asked = (CompanyMask)-1;
823  continue;
824  }
825 
826  SetBit(e->preview_asked, e->preview_company);
827  e->preview_wait = 20;
828  /* AIs are intentionally not skipped for preview even if they cannot build a certain
829  * vehicle type. This is done to not give poor performing human companies an "unfair"
830  * boost that they wouldn't have gotten against other human companies. The check on
831  * the line below is just to make AIs not notice that they have a preview if they
832  * cannot build the vehicle. */
833  if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
834  if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
835  }
836  }
837  }
838 }
839 
845 {
846  for (Engine *e : Engine::Iterate()) {
847  SB(e->company_hidden, cid, 1, 0);
848  }
849 }
850 
860 CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
861 {
862  Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
863  if (e == nullptr || _current_company >= MAX_COMPANIES) return CMD_ERROR;
864  if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
865 
866  if ((flags & DC_EXEC) != 0) {
867  SB(e->company_hidden, _current_company, 1, GB(p2, 31, 1));
869  }
870 
871  return CommandCost();
872 }
873 
884 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
885 {
886  Engine *e = Engine::GetIfValid(p1);
887  if (e == nullptr || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
888 
889  if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
890 
891  return CommandCost();
892 }
893 
900 {
901  EngineID index = e->index;
902 
903  /* In case the company didn't build the vehicle during the intro period,
904  * prevent that company from getting future intro periods for a while. */
905  if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
906  for (Company *c : Company::Iterate()) {
907  uint block_preview = c->block_preview;
908 
909  if (!HasBit(e->company_avail, c->index)) continue;
910 
911  /* We assume the user did NOT build it.. prove me wrong ;) */
912  c->block_preview = 20;
913 
914  for (const Vehicle *v : Vehicle::Iterate()) {
915  if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
916  (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
917  if (v->owner == c->index && v->engine_type == index) {
918  /* The user did prove me wrong, so restore old value */
919  c->block_preview = block_preview;
920  break;
921  }
922  }
923  }
924  }
925  }
926 
929 
930  /* Now available for all companies */
931  e->company_avail = (CompanyMask)-1;
932 
933  /* Do not introduce new rail wagons */
934  if (IsWagon(index)) return;
935 
936  if (e->type == VEH_TRAIN) {
937  /* maybe make another rail type available */
938  RailType railtype = e->u.rail.railtype;
939  assert(railtype < RAILTYPE_END);
940  for (Company *c : Company::Iterate()) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
941  } else if (e->type == VEH_ROAD) {
942  /* maybe make another road type available */
943  assert(e->u.road.roadtype < ROADTYPE_END);
944  for (Company* c : Company::Iterate()) c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes | GetRoadTypeInfo(e->u.road.roadtype)->introduces_roadtypes, _date);
945  }
946 
947  /* Only broadcast event if AIs are able to build this vehicle type. */
948  if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
949 
950  /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
951  if (!IsVehicleTypeDisabled(e->type, false)) {
952  SetDParam(0, GetEngineCategoryName(index));
953  SetDParam(1, index);
954  AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
955  }
956 
957  /* Update the toolbar. */
960 
961  /* Close pending preview windows */
963 }
964 
967 {
969  for (Engine *e : Engine::Iterate()) {
970  /* Age the vehicle */
971  if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
972  e->age++;
974  }
975 
976  /* Do not introduce invalid engines */
977  if (!e->IsEnabled()) continue;
978 
979  if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
980  /* Introduce it to all companies */
982  } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
983  /* Introduction date has passed...
984  * Check if it is allowed to build this vehicle type at all
985  * based on the current game settings. If not, it does not
986  * make sense to show the preview dialog to any company. */
987  if (IsVehicleTypeDisabled(e->type, false)) continue;
988 
989  /* Do not introduce new rail wagons */
990  if (IsWagon(e->index)) continue;
991 
992  /* Show preview dialog to one of the companies. */
993  e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
994  e->preview_company = INVALID_COMPANY;
995  e->preview_asked = 0;
996  }
997  }
998 
999  InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
1000  }
1001 }
1002 
1008 static bool IsUniqueEngineName(const char *name)
1009 {
1010  for (const Engine *e : Engine::Iterate()) {
1011  if (e->name != nullptr && strcmp(e->name, name) == 0) return false;
1012  }
1013 
1014  return true;
1015 }
1016 
1026 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1027 {
1028  Engine *e = Engine::GetIfValid(p1);
1029  if (e == nullptr) return CMD_ERROR;
1030 
1031  bool reset = StrEmpty(text);
1032 
1033  if (!reset) {
1035  if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1036  }
1037 
1038  if (flags & DC_EXEC) {
1039  free(e->name);
1040 
1041  if (reset) {
1042  e->name = nullptr;
1043  } else {
1044  e->name = stredup(text);
1045  }
1046 
1048  }
1049 
1050  return CommandCost();
1051 }
1052 
1053 
1063 {
1064  const Engine *e = Engine::GetIfValid(engine);
1065 
1066  /* check if it's an engine that is in the engine array */
1067  if (e == nullptr) return false;
1068 
1069  /* check if it's an engine of specified type */
1070  if (e->type != type) return false;
1071 
1072  /* check if it's available ... */
1073  if (company == OWNER_DEITY) {
1074  /* ... for any company (preview does not count) */
1075  if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1076  } else {
1077  /* ... for this company */
1078  if (!HasBit(e->company_avail, company)) return false;
1079  }
1080 
1081  if (!e->IsEnabled()) return false;
1082 
1083  if (type == VEH_TRAIN && company != OWNER_DEITY) {
1084  /* Check if the rail type is available to this company */
1085  const Company *c = Company::Get(company);
1086  if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1087  }
1088  if (type == VEH_ROAD && company != OWNER_DEITY) {
1089  /* Check if the road type is available to this company */
1090  const Company *c = Company::Get(company);
1091  if ((GetRoadTypeInfo(e->u.road.roadtype)->powered_roadtypes & c->avail_roadtypes) == ROADTYPES_NONE) return false;
1092  }
1093 
1094  return true;
1095 }
1096 
1104 {
1105  const Engine *e = Engine::GetIfValid(engine);
1106 
1107  /* check if it's an engine that is in the engine array */
1108  if (e == nullptr) return false;
1109 
1110  if (!e->CanCarryCargo()) return false;
1111 
1112  const EngineInfo *ei = &e->info;
1113  if (ei->refit_mask == 0) return false;
1114 
1115  /* Are there suffixes?
1116  * Note: This does not mean the suffixes are actually available for every consist at any time. */
1117  if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1118 
1119  /* Is there any cargo except the default cargo? */
1120  CargoID default_cargo = e->GetDefaultCargoType();
1121  CargoTypes default_cargo_mask = 0;
1122  SetBit(default_cargo_mask, default_cargo);
1123  return default_cargo != CT_INVALID && ei->refit_mask != default_cargo_mask;
1124 }
1125 
1130 {
1131  Date min_date = INT32_MAX;
1132 
1133  for (const Engine *e : Engine::Iterate()) {
1134  if (!e->IsEnabled()) continue;
1135 
1136  /* We have an available engine... yay! */
1137  if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1138 
1139  /* Okay, try to find the earliest date. */
1140  min_date = min(min_date, e->info.base_intro);
1141  }
1142 
1143  if (min_date < INT32_MAX) {
1144  SetDParam(0, min_date);
1145  ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1146  } else {
1147  ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);
1148  }
1149 }
AISettings ai
what may the AI do?
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition: engine.cpp:1062
Functions related to OTTD&#39;s strings.
Owner
Enum for all companies/owners.
Definition: company_type.h:18
VehicleSettings vehicle
options for vehicles
This vehicle is in the exclusive preview stage, either being used or being offered to a company...
Definition: engine_type.h:169
uint16 reliability_start
Initial reliability of the engine.
Definition: engine_base.h:27
uint16 reliability
Current reliability of the engine.
Definition: engine_base.h:25
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:79
Definition of stuff that is very close to a company, like the company struct itself.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:302
Functions for NewGRF engines.
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:304
static const int DAYS_IN_YEAR
days per year
Definition: date_type.h:29
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void CheckEngines()
Check for engines that have an appropriate availability.
Definition: engine.cpp:1129
StringID GetEngineCategoryName(EngineID engine)
Return the category of an engine.
Definition: engine_gui.cpp:38
void EnginesDailyLoop()
Daily check to offer an exclusive engine preview to the companies.
Definition: engine.cpp:801
void UnloadWagonOverrides(Engine *e)
Unload all wagon override sprite groups.
byte landscape
the landscape we&#39;re currently in
Aircraft range.
Functions related to the autoreplace GUIs.
static bool IsUniqueEngineName(const char *name)
Is name still free as name for an engine?
Definition: engine.cpp:1008
uint32 grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:158
bool IsEnabled() const
Checks whether the engine is a valid (non-articulated part of an) engine.
Definition: engine.cpp:150
StringID GetAircraftTypeText() const
Get the name of the aircraft type for display purposes.
Definition: engine.cpp:468
static CompanyID GetPreviewCompany(Engine *e)
Get the best company for an engine preview.
Definition: engine.cpp:754
Train vehicle type.
Definition: vehicle_type.h:24
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:291
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:171
Functions related to dates.
Power in hp (if dualheaded: sum of both vehicles)
Conventional Take Off and Landing, i.e. planes.
Definition: engine_type.h:92
const uint8 _engine_offsets[4]
Offset of the first engine of each vehicle type in original engine data.
Definition: engine.cpp:58
Stores the state of all random number generators.
Definition: random_func.hpp:33
uint16 GetRange() const
Get the range of an aircraft type.
Definition: engine.cpp:454
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
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
Replace vehicle window; Window numbers:
Definition: window_type.h:211
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:58
Date intro_date
Date of introduction of the engine.
Definition: engine_base.h:23
static const int GROUND_ACCELERATION
Acceleration due to gravity, 9.8 m/s^2.
Definition: vehicle_type.h:18
RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces)
Get the road types the given company can build.
Definition: road.cpp:188
Used for iterations.
Definition: road_type.h:26
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
Yearly runningcost (if dualheaded: sum of both vehicles)
static void RestoreRandomSeeds(const SavedRandomSeeds &storage)
Restores previously saved seeds.
Definition: random_func.hpp:52
void StartupOneEngine(Engine *e, Date aging_date)
Start/initialise one engine.
Definition: engine.cpp:640
void SetRandomSeed(uint32 seed)
(Re)set the state of the random number generators.
Definition: random_func.cpp:65
Transport over water.
Functions related to vehicles.
CargoTypes GetUnionOfArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type)
Ors the refit_masks of all articulated parts.
static bool IsWagon(EngineID index)
Determine whether an engine type is a wagon (and not a loco).
Definition: engine.cpp:567
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:65
CompanyMask company_hidden
Bit for each company whether the engine is normally hidden in the build gui for that company...
Definition: engine_base.h:38
Build vehicle; Window numbers:
Definition: window_type.h:376
Vehicle data structure.
Definition: vehicle_base.h:210
UnitID max_aircraft
max planes in game per company
New vehicle has become available.
Definition: news_type.h:33
Purchase cost (if dualheaded: sum of both vehicles)
static Year _year_engine_aging_stops
Year that engine aging stops.
Definition: engine.cpp:47
static const uint NUM_DEFAULT_ENGINES
Number of default entries.
Definition: engine_base.h:169
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:259
Tindex index
Index of this pool item.
Definition: pool_type.hpp:189
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:380
EngineID GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:510
Cargo capacity after refit.
Base for aircraft.
Tractive effort coefficient in 1/256.
Common return value for all commands.
Definition: command_type.h:23
int32 Year
Type for the year, note: 0 based, i.e. starts at the year 0.
Definition: date_type.h:18
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
static void NewVehicleAvailable(Engine *e)
An engine has become available for general use.
Definition: engine.cpp:899
byte flags
Flags of the engine.
Definition: engine_base.h:33
void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
Clear the &#39;hidden&#39; flag for all engines of a new company.
Definition: engine.cpp:844
bool never_expire_vehicles
never expire vehicles
CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Set the visibility of an engine.
Definition: engine.cpp:860
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:24
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition: engine_base.h:79
Date base_intro
Basic date of engine introduction (without random parts).
Definition: engine_type.h:133
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
Definition: aircraft.h:121
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:942
Year lifelength
Lifetime of a single vehicle.
Definition: engine_type.h:134
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
uint16 duration_phase_2
Second reliability phase in months, keeping reliability_max.
Definition: engine_base.h:31
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition: engine.cpp:160
RoadType roadtype
Road type.
Definition: engine_type.h:125
Pseudo random number generator.
uint16 multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:61
bool IsEngineRefittable(EngineID engine)
Check if an engine is refittable.
Definition: engine.cpp:1103
Invalid cargo type.
Definition: cargo_type.h:68
bool ai_disable_veh_train
disable types for AI
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:3334
static const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:224
Functions related to low-level strings.
Some methods of Pool are placed here in order to reduce compilation time and binary size...
uint16 reliability_spd_dec
Speed of reliability decay between services (per day).
Definition: engine_base.h:26
Money GetCost() const
Return how much a new engine costs.
Definition: engine.cpp:319
Engine preview window; Window numbers:
Definition: window_type.h:583
Information about a vehicle.
Definition: engine_type.h:132
uint16 internal_id
The internal ID within the GRF file.
Definition: engine_base.h:159
Other information.
Definition: error.h:22
Functions related to errors.
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power ...
Definition: road.h:119
byte cargo_subtype
Used for livery refits (NewGRF variations)
Definition: vehicle_base.h:304
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition: engine.cpp:543
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition: engine.cpp:615
RoadTypes AddDateIntroducedRoadTypes(RoadTypes current, Date date)
Add the road types that are to be introduced at the given date.
Definition: road.cpp:155
int8 retire_early
Number of years early to retire vehicle.
Definition: engine_type.h:144
UnitID max_roadveh
max trucks in game per company
Functions related to engines.
CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Accept an engine prototype.
Definition: engine.cpp:884
DoCommandFlag
List of flags for a command.
Definition: command_type.h:342
uint16 duration_phase_3
Third reliability phase on months, decaying to reliability_final.
Definition: engine_base.h:32
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:143
simple wagon, not motorized
Definition: engine_type.h:29
Stores the mapping of EngineID to the internal id of newgrfs.
Definition: engine_base.h:168
Capacity (if dualheaded: for each single vehicle)
Definition of base types and functions in a cross-platform compatible way.
Show suffix after cargo name.
Weight in 1/4 t.
uint16 duration_phase_1
First reliability phase in months, increasing reliability from reliability_start to reliability_max...
Definition: engine_base.h:30
Data structure to convert between Date and triplet (year, month, and day).
Definition: date_type.h:101
A number of safeguards to prevent using unsafe methods.
static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
Checks if a vehicle type is disabled for all/ai companies.
Definition: engine.cpp:788
RailTypes introduces_railtypes
Bitmask of which other railtypes are introduced when this railtype is introduced. ...
Definition: rail.h:263
Max. speed: 1 unit = 1/0.8 mph = 2 km-ish/h.
Engine GUI functions, used by build_vehicle_gui and autoreplace_gui
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
static const int CARGO_AGING_TICKS
cycle duration for aging cargo
Definition: date_type.h:35
CompanyMask company_avail
Bit for each company whether the engine is available for that company.
Definition: engine_base.h:37
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:136
uint16 reliability_max
Maximal reliability of the engine.
Definition: engine_base.h:28
static void CalcEngineReliability(Engine *e)
Update Engine::reliability and (if needed) update the engine GUIs.
Definition: engine.cpp:577
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:142
Year year
Year (0...)
Definition: date_type.h:102
Power in 10 HP.
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
uint16 reliability_final
Final reliability of the engine.
Definition: engine_base.h:29
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
bool ai_disable_veh_ship
disable types for AI
static bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
Definition: cargotype.h:148
char * name
Custom name of engine.
Definition: engine_base.h:22
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
const uint8 _engine_counts[4]
Number of engines of each vehicle type in original engine data.
Definition: engine.cpp:50
static void AcceptEnginePreview(EngineID eid, CompanyID company)
Company company accepts engine eid for preview.
Definition: engine.cpp:717
void DeleteWindowByClass(WindowClass cls)
Delete all windows of a given class.
Definition: window.cpp:1175
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:33
uint GetDisplayMaxSpeed() const
Returns max speed of the engine for display purposes.
Definition: engine.cpp:359
Base class for all pools.
Definition: pool_type.hpp:82
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition: ai_core.cpp:234
Build toolbar; Window numbers:
Definition: window_type.h:66
VehicleType type
The engine type.
Definition: engine_base.h:160
void StartupEngines()
Start/initialise all our engines.
Definition: engine.cpp:693
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don&#39;t get linker errors.
Definition: pool_func.hpp:224
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1162
static bool IsInteractiveCompany(CompanyID company)
Is the user representing company?
Definition: company_func.h:53
CompanyID preview_company
Company which is currently being offered a preview INVALID_COMPANY means no company.
Definition: engine_base.h:35
uint GetPower() const
Returns the power of the engine for display and sorting purposes.
Definition: engine.cpp:391
execute the given command
Definition: command_type.h:344
UnitID max_ships
max ships in game per company
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:174
Functions related to companies.
An invalid company.
Definition: company_type.h:30
Functions related to articulated vehicles.
Base class for engines.
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
uint32 generation_seed
noise seed for world generation
void EnginesMonthlyLoop()
Monthly update of the availability, reliability, and preview offers of the engines.
Definition: engine.cpp:966
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:340
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
Definition: engine.cpp:527
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:57
Refit capacity, the passed vehicle needs to have its ->cargo_type set to the cargo we are refitting t...
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
Max. speed: 1 unit = 1/3.2 mph = 0.5 km-ish/h.
CompanyMask preview_asked
Bit for each company which has already been offered a preview.
Definition: engine_base.h:34
indicates a combination of two locomotives
Definition: engine_type.h:28
RoadTypes avail_roadtypes
Road types available to this company.
Definition: company_base.h:121
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Rename an engine.
Definition: engine.cpp:1026
StringID string_id
Default name of engine.
Definition: engine_type.h:145
byte extend_vehicle_life
extend vehicle life by this many years
bool ai_disable_veh_aircraft
disable types for AI
Maximum number of companies.
Definition: company_type.h:23
#define MAX_DAY
The number of days till the last day.
Definition: date_type.h:95
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:261
Transport by road vehicle.
Default value to indicate that visual effect should be based on engine class.
Definition: vehicle_base.h:92
static uint CountBits(T value)
Counts the number of set bits in a variable.
uint8 substitute_id
The (original) entity ID to use if this GRF is not available (currently not used) ...
Definition: engine_base.h:161
Functions related to commands.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:45
uint16 local_id
id defined by the grf file for this entity
UnitID max_trains
max trains in game per company
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
Reference engine.
Definition: news_type.h:56
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
int32 Date
The type to store our dates in.
Definition: date_type.h:14
Tractive effort coefficient in 1/256.
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
uint8 original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition: engine_base.h:39
void AddRemoveEngineFromAutoreplaceAndBuildWindows(VehicleType type)
When an engine is made buildable or is removed from being buildable, add/remove it from the build/aut...
Money GetRunningCost() const
Return how much the running costs of this engine are.
Definition: engine.cpp:282
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:286
Used for iterations.
Definition: rail_type.h:33
Passengers.
Definition: cargotype.h:39
RailTypes avail_railtypes
Rail types available to this company.
Definition: company_base.h:120
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Base functions for all AIs.
static void SaveRandomSeeds(SavedRandomSeeds *storage)
Saves the current seeds.
Definition: random_func.hpp:42
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32 ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32 ref2=UINT32_MAX, void *free_data=nullptr)
Add a new newsitem to be shown.
Definition: news_gui.cpp:745
GameCreationSettings game_creation
settings used during the creation of a game (map)
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
uint16 cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:146
Weight in t (if dualheaded: for each single vehicle)
Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life...
Definition: engine_type.h:135
Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: date.cpp:147
static const uint MAX_LENGTH_ENGINE_NAME_CHARS
The maximum length of an engine name in characters including &#39;\0&#39;.
Definition: engine_type.h:172
RailTypes GetCompanyRailtypes(CompanyID company, bool introduces)
Get the rail types the given company can build.
Definition: rail.cpp:251
This vehicle is available to everyone.
Definition: engine_type.h:168
Window functions not directly related to making/drawing windows.
void ReloadNewGRFData()
Reload all NewGRF files during a running game.
Definition: afterload.cpp:3131
RoadTypes introduces_roadtypes
Bitmask of which other roadtypes are introduced when this roadtype is introduced. ...
Definition: road.h:174
uint GetDisplayWeight() const
Returns the weight of the engine for display purposes.
Definition: engine.cpp:409
Use the new capacity algorithm. The default cargotype of the vehicle does not affect capacity multipl...
Definition: engine_type.h:159
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3243
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.
bool ai_disable_veh_roadveh
disable types for AI
byte climates
Climates supported by the engine.
Definition: engine_type.h:138
Date _date
Current date in days (day counter)
Definition: date.cpp:26
Vehicle news item. (new engine available)
Definition: news_type.h:79
void ConvertDateToYMD(Date date, YearMonthDay *ymd)
Converts a Date to a Year, Month & Day.
Definition: date.cpp:92
uint GetDisplayMaxTractiveEffort() const
Returns the tractive effort of the engine for display purposes.
Definition: engine.cpp:427
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:44
The object is owned by a superuser / goal script.
Definition: company_type.h:27
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Definition: vehicle_func.h:89
RailTypes AddDateIntroducedRailTypes(RailTypes current, Date date)
Add the rail types that are to be introduced at the given date.
Definition: rail.cpp:218
Year starting_year
starting date
Road vehicle type.
Definition: vehicle_type.h:25
Date GetLifeLengthInDays() const
Returns the vehicle&#39;s (not model&#39;s!) life length in days.
Definition: engine.cpp:444
No roadtypes.
Definition: road_type.h:37
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:3316
static const int DAYS_IN_LEAP_YEAR
sometimes, you need one day more...
Definition: date_type.h:30
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1462
virtual void CleanPool()
Virtual method that deletes all items in the pool.
void ResetToDefaultMapping()
Initializes the EngineOverrideManager with the default engines.
Definition: engine.cpp:486
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:105
This file contains all the data for vehicles.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:199
Base for the NewGRF implementation.