OpenTTD: src/engine.cpp Source File

OpenTTD

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

- File List
- Globals

engine.cpp
Go to the documentation of this file.
1 /* $Id: engine.cpp 26802 2014-09-07 16:12:58Z alberth $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "command_func.h"
15 #include "news_func.h"
16 #include "aircraft.h"
17 #include "newgrf.h"
18 #include "newgrf_engine.h"
19 #include "strings_func.h"
20 #include "core/random_func.hpp"
21 #include "window_func.h"
22 #include "date_func.h"
23 #include "autoreplace_gui.h"
24 #include "string_func.h"
25 #include "ai/ai.hpp"
26 #include "core/pool_func.hpp"
27 #include "engine_gui.h"
28 #include "engine_func.h"
29 #include "engine_base.h"
30 #include "company_base.h"
31 #include "vehicle_func.h"
32 #include "articulated_vehicles.h"
33 #include "error.h"
34
35 #include "table/strings.h"
36 #include "table/engines.h"
37
38 #include "safeguards.h"
39
40 EnginePool _engine_pool("Engine");
41 INSTANTIATE_POOL_METHODS(Engine)
42
43 EngineOverrideManager _engine_mngr;
44
49 static Year _year_engine_aging_stops;
50
54 static uint16 _introduced_railtypes;
55
57 const uint8 _engine_counts[4] = {
58 lengthof(_orig_rail_vehicle_info),
59 lengthof(_orig_road_vehicle_info),
60 lengthof(_orig_ship_vehicle_info),
61 lengthof(_orig_aircraft_vehicle_info),
62 };
63
65 const uint8 _engine_offsets[4] = {
66 0,
67 lengthof(_orig_rail_vehicle_info),
68 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
69 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
70 };
71
72 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));
73
74 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
75
76 Engine::Engine() :
77 name(NULL),
78 overrides_count(0),
79 overrides(NULL)
80 {
81 }
82
83 Engine::Engine(VehicleType type, EngineID base)
84 {
85 this->type = type;
86 this->grf_prop.local_id = base;
87 this->list_position = base;
88
89 /* Check if this base engine is within the original engine data range */
90 if (base >= _engine_counts[type]) {
91 /* Set model life to maximum to make wagons available */
92 this->info.base_life = 0xFF;
93 /* Set road vehicle tractive effort to the default value */
94 if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
95 /* Aircraft must have CT_INVALID as default, as there is no property */
96 if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
97 /* Set visual effect to the default value */
98 switch (type) {
99 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
100 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
101 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
102 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
103 }
104 /* Set cargo aging period to the default value. */
105 this->info.cargo_age_period = CARGO_AGING_TICKS;
106 return;
107 }
108
109 /* Copy the original engine info for this slot */
110 this->info = _orig_engine_info[_engine_offsets[type] + base];
111
112 /* Copy the original engine data for this slot */
113 switch (type) {
114 default: NOT_REACHED();
115
116 case VEH_TRAIN:
117 this->u.rail = _orig_rail_vehicle_info[base];
118 this->original_image_index = this->u.rail.image_index;
119 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
120
121 /* Set the default model life of original wagons to "infinite" */
122 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
123
124 break;
125
126 case VEH_ROAD:
127 this->u.road = _orig_road_vehicle_info[base];
128 this->original_image_index = this->u.road.image_index;
129 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
130 break;
131
132 case VEH_SHIP:
133 this->u.ship = _orig_ship_vehicle_info[base];
134 this->original_image_index = this->u.ship.image_index;
135 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
136 break;
137
138 case VEH_AIRCRAFT:
139 this->u.air = _orig_aircraft_vehicle_info[base];
140 this->original_image_index = this->u.air.image_index;
141 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
142 break;
143 }
144 }
145
146 Engine::~Engine()
147 {
148 UnloadWagonOverrides(this);
149 free(this->name);
150 }
151
156 bool Engine::IsEnabled() const
157 {
158 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
159 }
160
166 uint32 Engine::GetGRFID() const
167 {
168 const GRFFile *file = this->GetGRF();
169 return file == NULL ? 0 : file->grfid;
170 }
171
177 bool Engine::CanCarryCargo() const
178 {
179 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
180 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
181 * for livery selection etc.
182 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
183 */
184 switch (this->type) {
185 case VEH_TRAIN:
186 if (this->u.rail.capacity == 0) return false;
187 break;
188
189 case VEH_ROAD:
190 if (this->u.road.capacity == 0) return false;
191 break;
192
193 case VEH_SHIP:
194 case VEH_AIRCRAFT:
195 break;
196
197 default: NOT_REACHED();
198 }
199 return this->GetDefaultCargoType() != CT_INVALID;
200 }
201
202
210 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
211 {
212 assert(v == NULL || this->index == v->engine_type);
213 if (mail_capacity != NULL) *mail_capacity = 0;
214
215 if (!this->CanCarryCargo()) return 0;
216
217 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
218 CargoID default_cargo = this->GetDefaultCargoType();
219 CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
220
221 if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
222 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
223 }
224
225 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
226 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
227 (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
228 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
229 if (callback != CALLBACK_FAILED) return callback;
230 }
231
232 /* Get capacity according to property resp. CB */
233 uint capacity;
234 uint extra_mail_cap = 0;
235 switch (this->type) {
236 case VEH_TRAIN:
237 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
238
239 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
240 if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
241 break;
242
243 case VEH_ROAD:
244 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
245 break;
246
247 case VEH_SHIP:
248 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
249 break;
250
251 case VEH_AIRCRAFT:
252 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
253 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
254 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
255 }
256 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
257 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
258 break;
259
260 default: NOT_REACHED();
261 }
262
263 if (!new_multipliers) {
264 /* Use the passenger multiplier for mail as well */
265 capacity += extra_mail_cap;
266 extra_mail_cap = 0;
267 }
268
269 /* Apply multipliers depending on cargo- and vehicletype. */
270 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
271 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
272 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
273 capacity *= cargo_multiplier;
274 if (extra_mail_cap > 0) {
275 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
276 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
277 }
278 capacity = (capacity + default_multiplier / 2) / default_multiplier;
279 }
280
281 return capacity;
282 }
283
288 Money Engine::GetRunningCost() const
289 {
290 Price base_price;
291 uint cost_factor;
292 switch (this->type) {
293 case VEH_ROAD:
294 base_price = this->u.road.running_cost_class;
295 if (base_price == INVALID_PRICE) return 0;
296 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
297 break;
298
299 case VEH_TRAIN:
300 base_price = this->u.rail.running_cost_class;
301 if (base_price == INVALID_PRICE) return 0;
302 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
303 break;
304
305 case VEH_SHIP:
306 base_price = PR_RUNNING_SHIP;
307 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
308 break;
309
310 case VEH_AIRCRAFT:
311 base_price = PR_RUNNING_AIRCRAFT;
312 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
313 break;
314
315 default: NOT_REACHED();
316 }
317
318 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
319 }
320
325 Money Engine::GetCost() const
326 {
327 Price base_price;
328 uint cost_factor;
329 switch (this->type) {
330 case VEH_ROAD:
331 base_price = PR_BUILD_VEHICLE_ROAD;
332 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
333 break;
334
335 case VEH_TRAIN:
336 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
337 base_price = PR_BUILD_VEHICLE_WAGON;
338 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
339 } else {
340 base_price = PR_BUILD_VEHICLE_TRAIN;
341 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
342 }
343 break;
344
345 case VEH_SHIP:
346 base_price = PR_BUILD_VEHICLE_SHIP;
347 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
348 break;
349
350 case VEH_AIRCRAFT:
351 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
352 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
353 break;
354
355 default: NOT_REACHED();
356 }
357
358 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
359 }
360
365 uint Engine::GetDisplayMaxSpeed() const
366 {
367 switch (this->type) {
368 case VEH_TRAIN:
369 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
370
371 case VEH_ROAD: {
372 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
373 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
374 }
375
376 case VEH_SHIP:
377 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
378
379 case VEH_AIRCRAFT: {
380 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
381 if (max_speed != 0) {
382 return (max_speed * 128) / 10;
383 }
384 return this->u.air.max_speed;
385 }
386
387 default: NOT_REACHED();
388 }
389 }
390
397 uint Engine::GetPower() const
398 {
399 /* Only trains and road vehicles have 'power'. */
400 switch (this->type) {
401 case VEH_TRAIN:
402 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
403 case VEH_ROAD:
404 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
405
406 default: NOT_REACHED();
407 }
408 }
409
415 uint Engine::GetDisplayWeight() const
416 {
417 /* Only trains and road vehicles have 'weight'. */
418 switch (this->type) {
419 case VEH_TRAIN:
420 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
421 case VEH_ROAD:
422 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
423
424 default: NOT_REACHED();
425 }
426 }
427
433 uint Engine::GetDisplayMaxTractiveEffort() const
434 {
435 /* Only trains and road vehicles have 'tractive effort'. */
436 switch (this->type) {
437 case VEH_TRAIN:
438 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
439 case VEH_ROAD:
440 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
441
442 default: NOT_REACHED();
443 }
444 }
445
450 Date Engine::GetLifeLengthInDays() const
451 {
452 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
453 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
454 }
455
460 uint16 Engine::GetRange() const
461 {
462 switch (this->type) {
463 case VEH_AIRCRAFT:
464 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
465
466 default: NOT_REACHED();
467 }
468 }
469
473 void EngineOverrideManager::ResetToDefaultMapping()
474 {
475 this->Clear();
476 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
477 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
478 EngineIDMapping *eid = this->Append();
479 eid->type = type;
480 eid->grfid = INVALID_GRFID;
481 eid->internal_id = internal_id;
482 eid->substitute_id = internal_id;
483 }
484 }
485 }
486
496 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
497 {
498 const EngineIDMapping *end = this->End();
499 EngineID index = 0;
500 for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
501 if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
502 return index;
503 }
504 }
505 return INVALID_ENGINE;
506 }
507
513 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
514 {
515 const Vehicle *v;
516 FOR_ALL_VEHICLES(v) {
517 if (IsCompanyBuildableVehicleType(v)) return false;
518 }
519
520 /* Reset the engines, they will get new EngineIDs */
521 _engine_mngr.ResetToDefaultMapping();
522 ReloadNewGRFData();
523
524 return true;
525 }
526
530 void SetupEngines()
531 {
532 DeleteWindowByClass(WC_ENGINE_PREVIEW);
533 _engine_pool.CleanPool();
534
535 assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
536 const EngineIDMapping *end = _engine_mngr.End();
537 uint index = 0;
538 for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
539 /* Assert is safe; there won't be more than 256 original vehicles
540 * in any case, and we just cleaned the pool. */
541 assert(Engine::CanAllocateItem());
542 const Engine *e = new Engine(eid->type, eid->internal_id);
543 assert(e->index == index);
544 }
545
546 _introduced_railtypes = 0;
547 }
548
552 static void CheckRailIntroduction()
553 {
554 /* All railtypes have been introduced. */
555 if (_introduced_railtypes == UINT16_MAX || Company::GetPoolSize() == 0) return;
556
557 /* We need to find the railtypes that are known to all companies. */
558 RailTypes rts = (RailTypes)UINT16_MAX;
559
560 /* We are at, or past the introduction date of the rail. */
561 Company *c;
562 FOR_ALL_COMPANIES(c) {
563 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
564 rts &= c->avail_railtypes;
565 }
566
567 _introduced_railtypes |= rts;
568 }
569
570 void ShowEnginePreviewWindow(EngineID engine);
571
577 static bool IsWagon(EngineID index)
578 {
579 const Engine *e = Engine::Get(index);
580 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
581 }
582
587 static void CalcEngineReliability(Engine *e)
588 {
589 uint age = e->age;
590
591 /* Check for early retirement */
592 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
593 int retire_early = e->info.retire_early;
594 uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
595 if (retire_early != 0 && age >= retire_early_max_age) {
596 /* Early retirement is enabled and we're past the date... */
597 e->company_avail = 0;
598 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
599 }
600 }
601
602 if (age < e->duration_phase_1) {
603 uint start = e->reliability_start;
604 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
605 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
606 /* We are at the peak of this engines life. It will have max reliability.
607 * This is also true if the engines never expire. They will not go bad over time */
608 e->reliability = e->reliability_max;
609 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
610 uint max = e->reliability_max;
611 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
612 } else {
613 /* time's up for this engine.
614 * We will now completely retire this design */
615 e->company_avail = 0;
616 e->reliability = e->reliability_final;
617 /* Kick this engine out of the lists */
618 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
619 }
620 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
621 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
622 }
623
625 void SetYearEngineAgingStops()
626 {
627 /* Determine last engine aging year, default to 2050 as previously. */
628 _year_engine_aging_stops = 2050;
629
630 const Engine *e;
631 FOR_ALL_ENGINES(e) {
632 const EngineInfo *ei = &e->info;
633
634 /* Exclude certain engines */
635 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
636 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
637
638 /* Base year ending date on half the model life */
639 YearMonthDay ymd;
640 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
641
642 _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
643 }
644 }
645
651 void StartupOneEngine(Engine *e, Date aging_date)
652 {
653 const EngineInfo *ei = &e->info;
654
655 e->age = 0;
656 e->flags = 0;
657 e->company_avail = 0;
658 e->company_hidden = 0;
659
660 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
661 * of engines in early starting games.
662 * Note: TTDP uses fixed 1922 */
663 uint32 r = Random();
664 e->intro_date = ei->base_intro <= ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : (Date)GB(r, 0, 9) + ei->base_intro;
665 if (e->intro_date <= _date) {
666 e->age = (aging_date - e->intro_date) >> 5;
667 e->company_avail = (CompanyMask)-1;
668 e->flags |= ENGINE_AVAILABLE;
669 }
670
671 e->reliability_start = GB(r, 16, 14) + 0x7AE0;
672 r = Random();
673 e->reliability_max = GB(r, 0, 14) + 0xBFFF;
674 e->reliability_final = GB(r, 16, 14) + 0x3FFF;
675
676 r = Random();
677 e->duration_phase_1 = GB(r, 0, 5) + 7;
678 e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
679 e->duration_phase_3 = GB(r, 9, 7) + 120;
680
681 e->reliability_spd_dec = ei->decay_speed << 2;
682
683 CalcEngineReliability(e);
684
685 /* prevent certain engines from ever appearing. */
686 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
687 e->flags |= ENGINE_AVAILABLE;
688 e->company_avail = 0;
689 }
690 }
691
696 void StartupEngines()
697 {
698 Engine *e;
699 /* Aging of vehicles stops, so account for that when starting late */
700 const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
701
702 FOR_ALL_ENGINES(e) {
703 StartupOneEngine(e, aging_date);
704 }
705
706 /* Update the bitmasks for the vehicle lists */
707 Company *c;
708 FOR_ALL_COMPANIES(c) {
709 c->avail_railtypes = GetCompanyRailtypes(c->index);
710 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
711 }
712
713 /* Rail types that are invalid or never introduced are marked as
714 * being introduced upon start. That way we can easily check whether
715 * there is any date related introduction that is still going to
716 * happen somewhere in the future. */
717 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
718 const RailtypeInfo *rti = GetRailTypeInfo(rt);
719 if (rti->label != 0 && IsInsideMM(rti->introduction_date, 0, MAX_DAY)) continue;
720
721 SetBit(_introduced_railtypes, rt);
722 }
723
724 CheckRailIntroduction();
725
726 /* Invalidate any open purchase lists */
727 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
728 }
729
735 static void AcceptEnginePreview(EngineID eid, CompanyID company)
736 {
737 Engine *e = Engine::Get(eid);
738 Company *c = Company::Get(company);
739
740 SetBit(e->company_avail, company);
741 if (e->type == VEH_TRAIN) {
742 assert(e->u.rail.railtype < RAILTYPE_END);
743 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
744 } else if (e->type == VEH_ROAD) {
745 SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
746 }
747
748 e->preview_company = INVALID_COMPANY;
749 e->preview_asked = (CompanyMask)-1;
750 if (company == _local_company) {
751 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
752 }
753
754 /* Update the toolbar. */
755 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
756 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
757
758 /* Notify preview window, that it might want to close.
759 * Note: We cannot directly close the window.
760 * In singleplayer this function is called from the preview window, so
761 * we have to use the GUI-scope scheduling of InvalidateWindowData.
762 */
763 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
764 }
765
771 static CompanyID GetPreviewCompany(Engine *e)
772 {
773 CompanyID best_company = INVALID_COMPANY;
774
775 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
776 uint32 cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : (uint32)-1;
777
778 int32 best_hist = -1;
779 const Company *c;
780 FOR_ALL_COMPANIES(c) {
781 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
782 c->old_economy[0].performance_history > best_hist) {
783
784 /* Check whether the company uses similar vehicles */
785 Vehicle *v;
786 FOR_ALL_VEHICLES(v) {
787 if (v->owner != c->index || v->type != e->type) continue;
788 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
789
790 best_hist = c->old_economy[0].performance_history;
791 best_company = c->index;
792 break;
793 }
794 }
795 }
796
797 return best_company;
798 }
799
807 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
808 {
809 switch (type) {
810 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
811 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
812 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
813 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
814
815 default: NOT_REACHED();
816 }
817 }
818
820 void EnginesDailyLoop()
821 {
822 CheckRailIntroduction();
823
824 if (_cur_year >= _year_engine_aging_stops) return;
825
826 Engine *e;
827 FOR_ALL_ENGINES(e) {
828 EngineID i = e->index;
829 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
830 if (e->preview_company != INVALID_COMPANY) {
831 if (!--e->preview_wait) {
832 DeleteWindowById(WC_ENGINE_PREVIEW, i);
833 e->preview_company = INVALID_COMPANY;
834 }
835 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
836 e->preview_company = GetPreviewCompany(e);
837
838 if (e->preview_company == INVALID_COMPANY) {
839 e->preview_asked = (CompanyMask)-1;
840 continue;
841 }
842
843 SetBit(e->preview_asked, e->preview_company);
844 e->preview_wait = 20;
845 /* AIs are intentionally not skipped for preview even if they cannot build a certain
846 * vehicle type. This is done to not give poor performing human companies an "unfair"
847 * boost that they wouldn't have gotten against other human companies. The check on
848 * the line below is just to make AIs not notice that they have a preview if they
849 * cannot build the vehicle. */
850 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
851 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
852 }
853 }
854 }
855 }
856
861 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
862 {
863 Engine *e;
864 FOR_ALL_ENGINES(e) {
865 SB(e->company_hidden, cid, 1, 0);
866 }
867 }
868
878 CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
879 {
880 Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
881 if (e == NULL || _current_company >= MAX_COMPANIES) return CMD_ERROR;
882 if ((e->flags & ENGINE_AVAILABLE) == 0 || !HasBit(e->company_avail, _current_company)) return CMD_ERROR;
883
884 if ((flags & DC_EXEC) != 0) {
885 SB(e->company_hidden, _current_company, 1, GB(p2, 31, 1));
886 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
887 }
888
889 return CommandCost();
890 }
891
902 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
903 {
904 Engine *e = Engine::GetIfValid(p1);
905 if (e == NULL || e->preview_company != _current_company) return CMD_ERROR;
906
907 if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
908
909 return CommandCost();
910 }
911
917 static void NewVehicleAvailable(Engine *e)
918 {
919 Vehicle *v;
920 Company *c;
921 EngineID index = e->index;
922
923 /* In case the company didn't build the vehicle during the intro period,
924 * prevent that company from getting future intro periods for a while. */
925 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
926 FOR_ALL_COMPANIES(c) {
927 uint block_preview = c->block_preview;
928
929 if (!HasBit(e->company_avail, c->index)) continue;
930
931 /* We assume the user did NOT build it.. prove me wrong ;) */
932 c->block_preview = 20;
933
934 FOR_ALL_VEHICLES(v) {
935 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
936 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
937 if (v->owner == c->index && v->engine_type == index) {
938 /* The user did prove me wrong, so restore old value */
939 c->block_preview = block_preview;
940 break;
941 }
942 }
943 }
944 }
945 }
946
947 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
948 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
949
950 /* Now available for all companies */
951 e->company_avail = (CompanyMask)-1;
952
953 /* Do not introduce new rail wagons */
954 if (IsWagon(index)) return;
955
956 if (e->type == VEH_TRAIN) {
957 /* maybe make another rail type available */
958 RailType railtype = e->u.rail.railtype;
959 assert(railtype < RAILTYPE_END);
960 FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
961 } else if (e->type == VEH_ROAD) {
962 /* maybe make another road type available */
963 FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
964 }
965
966 /* Only broadcast event if AIs are able to build this vehicle type. */
967 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
968
969 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
970 if (!IsVehicleTypeDisabled(e->type, false)) {
971 SetDParam(0, GetEngineCategoryName(index));
972 SetDParam(1, index);
973 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
974 }
975
976 /* Update the toolbar. */
977 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
978 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
979
980 /* Close pending preview windows */
981 DeleteWindowById(WC_ENGINE_PREVIEW, index);
982 }
983
985 void EnginesMonthlyLoop()
986 {
987 if (_cur_year < _year_engine_aging_stops) {
988 Engine *e;
989 FOR_ALL_ENGINES(e) {
990 /* Age the vehicle */
991 if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
992 e->age++;
993 CalcEngineReliability(e);
994 }
995
996 /* Do not introduce invalid engines */
997 if (!e->IsEnabled()) continue;
998
999 if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
1000 /* Introduce it to all companies */
1001 NewVehicleAvailable(e);
1002 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
1003 /* Introduction date has passed...
1004 * Check if it is allowed to build this vehicle type at all
1005 * based on the current game settings. If not, it does not
1006 * make sense to show the preview dialog to any company. */
1007 if (IsVehicleTypeDisabled(e->type, false)) continue;
1008
1009 /* Do not introduce new rail wagons */
1010 if (IsWagon(e->index)) continue;
1011
1012 /* Show preview dialog to one of the companies. */
1013 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
1014 e->preview_company = INVALID_COMPANY;
1015 e->preview_asked = 0;
1016 }
1017 }
1018
1019 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
1020 }
1021 }
1022
1028 static bool IsUniqueEngineName(const char *name)
1029 {
1030 const Engine *e;
1031
1032 FOR_ALL_ENGINES(e) {
1033 if (e->name != NULL && strcmp(e->name, name) == 0) return false;
1034 }
1035
1036 return true;
1037 }
1038
1048 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1049 {
1050 Engine *e = Engine::GetIfValid(p1);
1051 if (e == NULL) return CMD_ERROR;
1052
1053 bool reset = StrEmpty(text);
1054
1055 if (!reset) {
1056 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1057 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1058 }
1059
1060 if (flags & DC_EXEC) {
1061 free(e->name);
1062
1063 if (reset) {
1064 e->name = NULL;
1065 } else {
1066 e->name = stredup(text);
1067 }
1068
1069 MarkWholeScreenDirty();
1070 }
1071
1072 return CommandCost();
1073 }
1074
1075
1084 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1085 {
1086 const Engine *e = Engine::GetIfValid(engine);
1087
1088 /* check if it's an engine that is in the engine array */
1089 if (e == NULL) return false;
1090
1091 /* check if it's an engine of specified type */
1092 if (e->type != type) return false;
1093
1094 /* check if it's available ... */
1095 if (company == OWNER_DEITY) {
1096 /* ... for any company (preview does not count) */
1097 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1098 } else {
1099 /* ... for this company */
1100 if (!HasBit(e->company_avail, company)) return false;
1101 }
1102
1103 if (!e->IsEnabled()) return false;
1104
1105 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1106 /* Check if the rail type is available to this company */
1107 const Company *c = Company::Get(company);
1108 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1109 }
1110
1111 return true;
1112 }
1113
1120 bool IsEngineRefittable(EngineID engine)
1121 {
1122 const Engine *e = Engine::GetIfValid(engine);
1123
1124 /* check if it's an engine that is in the engine array */
1125 if (e == NULL) return false;
1126
1127 if (!e->CanCarryCargo()) return false;
1128
1129 const EngineInfo *ei = &e->info;
1130 if (ei->refit_mask == 0) return false;
1131
1132 /* Are there suffixes?
1133 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1134 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1135
1136 /* Is there any cargo except the default cargo? */
1137 CargoID default_cargo = e->GetDefaultCargoType();
1138 return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
1139 }
1140
1144 void CheckEngines()
1145 {
1146 const Engine *e;
1147 Date min_date = INT32_MAX;
1148
1149 FOR_ALL_ENGINES(e) {
1150 if (!e->IsEnabled()) continue;
1151
1152 /* We have an available engine... yay! */
1153 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1154
1155 /* Okay, try to find the earliest date. */
1156 min_date = min(min_date, e->info.base_intro);
1157 }
1158
1159 if (min_date < INT32_MAX) {
1160 SetDParam(0, min_date);
1161 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1162 } else {
1163 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);
1164 }
1165 }