OpenTTD Source 20261112-master-gbcbec5e63f
vehicle_sl.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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11
12#include "saveload.h"
13#include "saveload_error.hpp"
15
16#include "../debug.h"
17#include "../vehicle_func.h"
18#include "../train.h"
19#include "../roadveh.h"
20#include "../ship.h"
21#include "../aircraft.h"
22#include "../timetable.h"
23#include "../station_base.h"
25#include "../company_base.h"
26#include "../company_func.h"
27#include "../disaster_vehicle.h"
28#include "../economy_base.h"
29
30#include "../safeguards.h"
31
37{
38 for (Train *v : Train::Iterate()) {
39 v->other_multiheaded_part = nullptr;
40 }
41
42 for (Train *v : Train::Iterate()) {
43 if (v->IsFrontEngine() || v->IsFreeWagon()) {
44 /* Two ways to associate multiheaded parts to each other:
45 * sequential-matching: Trains shall be arranged to look like <..>..<..>..<..>..
46 * bracket-matching: Free vehicle chains shall be arranged to look like ..<..<..>..<..>..>..
47 *
48 * Note: Old savegames might contain chains which do not comply with these rules, e.g.
49 * - the front and read parts have invalid orders
50 * - different engine types might be combined
51 * - there might be different amounts of front and rear parts.
52 *
53 * Note: The multiheaded parts need to be matched exactly like they are matched on the server, else desyncs will occur.
54 * This is why two matching strategies are needed.
55 */
56
57 bool sequential_matching = v->IsFrontEngine();
58
59 for (Train *u = v; u != nullptr; u = u->GetNextVehicle()) {
60 if (u->other_multiheaded_part != nullptr) continue; // we already linked this one
61
62 if (u->IsMultiheaded()) {
63 if (!u->IsEngine()) {
64 /* we got a rear car without a front car. We will convert it to a front one */
65 u->SetEngine();
66 u->spritenum--;
67 }
68
69 /* Find a matching back part */
70 EngineID eid = u->engine_type;
71 Train *w;
72 if (sequential_matching) {
73 for (w = u->GetNextVehicle(); w != nullptr; w = w->GetNextVehicle()) {
74 if (w->engine_type != eid || w->other_multiheaded_part != nullptr || !w->IsMultiheaded()) continue;
75
76 /* we found a car to partner with this engine. Now we will make sure it face the right way */
77 if (w->IsEngine()) {
78 w->ClearEngine();
79 w->spritenum++;
80 }
81 break;
82 }
83 } else {
84 uint stack_pos = 0;
85 for (w = u->GetNextVehicle(); w != nullptr; w = w->GetNextVehicle()) {
86 if (w->engine_type != eid || w->other_multiheaded_part != nullptr || !w->IsMultiheaded()) continue;
87
88 if (w->IsEngine()) {
89 stack_pos++;
90 } else {
91 if (stack_pos == 0) break;
92 stack_pos--;
93 }
94 }
95 }
96
97 if (w != nullptr) {
100 } else {
101 /* we got a front car and no rear cars. We will fake this one for forget that it should have been multiheaded */
102 u->ClearMultiheaded();
103 }
104 }
105 }
106 }
107 }
108}
109
115{
116 for (Train *t : Train::Iterate()) SetBit(t->subtype, 7); // indicates that it's the old format and needs to be converted in the next loop
117
118 for (Train *t : Train::Iterate()) {
119 if (HasBit(t->subtype, 7) && ((t->subtype & ~0x80) == 0 || (t->subtype & ~0x80) == 4)) {
120 for (Train *u = t; u != nullptr; u = u->Next()) {
121 const RailVehicleInfo *rvi = RailVehInfo(u->engine_type);
122
123 ClrBit(u->subtype, 7);
124 switch (u->subtype) {
125 case 0: // TS_Front_Engine
126 if (rvi->railveh_type == RailVehicleType::Multihead) u->SetMultiheaded();
127 u->SetFrontEngine();
128 u->SetEngine();
129 break;
130
131 case 1: // TS_Artic_Part
132 u->subtype = 0;
133 u->SetArticulatedPart();
134 break;
135
136 case 2: // TS_Not_First
137 u->subtype = 0;
139 /* normal wagon */
140 u->SetWagon();
141 break;
142 }
143 if (rvi->railveh_type == RailVehicleType::Multihead && rvi->image_index == u->spritenum - 1) {
144 /* rear end of a multiheaded engine */
145 u->SetMultiheaded();
146 break;
147 }
148 if (rvi->railveh_type == RailVehicleType::Multihead) u->SetMultiheaded();
149 u->SetEngine();
150 break;
151
152 case 4: // TS_Free_Car
153 u->subtype = 0;
154 u->SetWagon();
155 u->SetFreeWagon();
156 break;
157 default: SlErrorCorrupt("Invalid train subtype");
158 }
159 }
160 }
161 }
162}
163
164
167{
168 /* set airport_flags to 0 for all airports just to be sure */
169 for (Station *st : Station::Iterate()) {
170 st->airport.blocks = {}; // reset airport
171 }
172
173 for (Aircraft *a : Aircraft::Iterate()) {
174 /* airplane has another vehicle with subtype 4 (shadow), helicopter also has 3 (rotor)
175 * skip those */
176 if (a->IsNormalAircraft()) {
177 /* airplane in terminal stopped doesn't hurt anyone, so goto next */
178 if (a->vehstatus.Test(VehState::Stopped) && a->state == 0) {
179 a->state = HANGAR;
180 continue;
181 }
182
183 AircraftLeaveHangar(a, a->direction); // make airplane visible if it was in a depot for example
184 a->vehstatus.Reset(VehState::Stopped); // make airplane moving
186 a->cur_speed = a->vcache.cached_max_speed; // so aircraft don't have zero speed while in air
187 if (!a->current_order.IsType(OT_GOTO_STATION) && !a->current_order.IsType(OT_GOTO_DEPOT)) {
188 /* reset current order so aircraft doesn't have invalid "station-only" order */
189 a->current_order.MakeDummy();
190 }
191 a->state = FLYING;
192 AircraftNextAirportPos_and_Order(a); // move it to the entry point of the airport
194 a->tile = TileIndex{}; // aircraft in air is tile=0
195
196 /* correct speed of helicopter-rotors */
197 if (a->subtype == AIR_HELICOPTER) a->Next()->Next()->cur_speed = 32;
198
199 /* set new position x,y,z */
200 GetAircraftFlightLevelBounds(a, &a->z_pos, nullptr);
201 SetAircraftPosition(a, gp.x, gp.y, GetAircraftFlightLevel(a));
202 }
203 }
204
205 /* Clear aircraft from loading vehicles, if we bumped them into the air. */
206 for (Station *st : Station::Iterate()) {
207 for (auto iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); /* nothing */) {
208 Vehicle *v = *iter;
209 if (v->type == VehicleType::Aircraft && !v->current_order.IsType(OT_LOADING)) {
210 iter = st->loading_vehicles.erase(iter);
211 delete v->cargo_payment;
212 } else {
213 ++iter;
214 }
215 }
216 }
217}
218
227{
228 size_t total_engines = Engine::GetPoolSize();
229 VehicleTypeIndexArray<EngineID> first_engine = { EngineID::Invalid(), EngineID::Invalid(), EngineID::Invalid(), EngineID::Invalid() };
230
231 for (const Engine *e : Engine::IterateType(VehicleType::Train)) { first_engine[VehicleType::Train] = e->index; break; }
232 for (const Engine *e : Engine::IterateType(VehicleType::Road)) { first_engine[VehicleType::Road] = e->index; break; }
233 for (const Engine *e : Engine::IterateType(VehicleType::Ship)) { first_engine[VehicleType::Ship] = e->index; break; }
234 for (const Engine *e : Engine::IterateType(VehicleType::Aircraft)) { first_engine[VehicleType::Aircraft] = e->index; break; }
235
236 for (Vehicle *v : Vehicle::Iterate()) {
237 /* Test if engine types match */
238 switch (v->type) {
243 if (v->engine_type >= total_engines || v->type != v->GetEngine()->type) {
244 v->engine_type = first_engine[v->type];
245 }
246 break;
247
248 default:
249 break;
250 }
251 }
252}
253
254extern uint8_t _age_cargo_skip_counter; // From misc_sl.cpp
255
260void AfterLoadVehiclesPhase1(bool part_of_load)
261{
262 for (Vehicle *v : Vehicle::Iterate()) {
263 /* Reinstate the previous pointer */
264 if (v->Next() != nullptr) v->Next()->previous = v;
265 if (v->NextShared() != nullptr) v->NextShared()->previous_shared = v;
266
267 if (part_of_load) v->fill_percent_te_id = INVALID_TE_ID;
268 v->first = nullptr;
269 v->last = nullptr;
270 if (v->IsGroundVehicle()) v->GetGroundVehicleCache()->first_engine = EngineID::Invalid();
271 }
272
273 /* AfterLoadVehicles may also be called in case of NewGRF reload, in this
274 * case we may not convert orders again. */
275 if (part_of_load) {
276 /* Create shared vehicle chain for very old games (pre 5,2) and create
277 * OrderList from shared vehicle chains. For this to work correctly, the
278 * following conditions must be fulfilled:
279 * a) both next_shared and previous_shared are not set for pre 5,2 games
280 * b) both next_shared and previous_shared are set for later games
281 */
282 std::map<uint32_t, OrderList *> mapping;
283
284 for (Vehicle *v : Vehicle::Iterate()) {
285 if (v->orders != nullptr) {
286 if (IsSavegameVersionBefore(SaveLoadVersion::OrderList)) { // Pre-105 didn't save an OrderList
287 if (mapping[v->old_orders] == nullptr) {
288 /* This adds the whole shared vehicle chain for case b */
289
290 /* Creating an OrderList here is safe because the number of vehicles
291 * allowed in these savegames matches the number of OrderLists. As
292 * such each vehicle can get an OrderList and it will (still) fit. */
294 std::vector<Order> orders;
295 for (const OldOrderSaveLoadItem *old_order = GetOldOrder(v->old_orders); old_order != nullptr; old_order = GetOldOrder(old_order->next)) {
296 orders.push_back(std::move(old_order->order));
297 }
298 v->orders = mapping[v->old_orders] = OrderList::Create(std::move(orders), v);
299 } else {
300 v->orders = mapping[v->old_orders];
301 /* For old games (case a) we must create the shared vehicle chain */
303 v->AddToShared(v->orders->GetFirstSharedVehicle());
304 }
305 }
306 } else { // OrderList was saved as such, only recalculate not saved values
307 if (v->PreviousShared() == nullptr) {
308 v->orders->Initialize(v);
309 }
310 }
311 }
312 }
313 }
314
315 for (Vehicle *v : Vehicle::Iterate()) {
316 /* Fill the first pointers. */
317 if (v->Previous() == nullptr) {
318 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
319 u->first = v;
320 }
321 }
322
323 /* Fill the last pointers. */
324 if (v->Next() == nullptr) {
325 for (Vehicle *u = v; u != nullptr; u = u->Previous()) {
326 u->last = v;
327 }
328 }
329 }
330
331 if (part_of_load) {
333 /* Before 105 there was no order for shared orders, thus it messed up horribly */
334 for (Vehicle *v : Vehicle::Iterate()) {
335 if (v->First() != v || v->orders != nullptr || v->previous_shared != nullptr || v->next_shared == nullptr) continue;
336
337 /* As above, allocating OrderList here is safe. */
339 v->orders = OrderList::Create();
340 v->orders->first_shared = v;
341 for (Vehicle *u = v; u != nullptr; u = u->next_shared) {
342 u->orders = v->orders;
343 }
344 }
345 }
346
348 /* The road vehicle subtype was converted to a flag. */
349 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
350 if (rv->subtype == 0) {
351 /* The road vehicle is at the front. */
352 rv->SetFrontEngine();
353 } else if (rv->subtype == 1) {
354 /* The road vehicle is an articulated part. */
355 rv->subtype = 0;
356 rv->SetArticulatedPart();
357 } else {
358 SlErrorCorrupt("Invalid road vehicle subtype");
359 }
360 }
361 }
362
364 /* In some old savegames there might be some "crap" stored. */
365 for (Vehicle *v : Vehicle::Iterate()) {
366 if (!v->IsPrimaryVehicle() && v->type != VehicleType::Disaster) {
367 v->current_order.Free();
368 v->unitnumber = 0;
369 }
370 }
371 }
372
374 /* Set the vehicle-local cargo age counter from the old global counter. */
375 for (Vehicle *v : Vehicle::Iterate()) {
376 v->cargo_age_counter = _age_cargo_skip_counter;
377 }
378 }
379
381 /* Set service interval flags */
382 for (Vehicle *v : Vehicle::Iterate()) {
383 if (!v->IsPrimaryVehicle()) continue;
384
385 const Company *c = Company::Get(v->owner);
386 int interval = CompanyServiceInterval(c, v->type);
387
388 v->SetServiceIntervalIsCustom(v->GetServiceInterval() != interval);
389 v->SetServiceIntervalIsPercent(c->settings.vehicle.servint_ispercent);
390 }
391 }
392
394 /* Ship rotation added */
395 for (Ship *s : Ship::Iterate()) {
396 s->rotation = s->direction;
397 }
398 } else {
399 for (Ship *s : Ship::Iterate()) {
400 if (s->rotation == s->direction) continue;
401 /* In case we are rotating on gameload, set the rotation position to
402 * the current position, otherwise the applied workaround offset would
403 * be with respect to 0,0.
404 */
405 s->rotation_x_pos = s->x_pos;
406 s->rotation_y_pos = s->y_pos;
407 }
408 }
409
411 /* Convert timetable start from a date to an absolute tick in TimerGameTick::counter. */
412 for (Vehicle *v : Vehicle::Iterate()) {
413 /* If the start date is 0, the vehicle is not waiting to start and can be ignored. */
414 if (v->timetable_start == 0) continue;
415
416 v->timetable_start = GetStartTickFromDate(TimerGameEconomy::Date(v->timetable_start));
417 }
418 }
419
421 /* Set vehicle economy age based on calendar age. */
422 for (Vehicle *v : Vehicle::Iterate()) {
423 v->economy_age = TimerGameEconomy::Date{v->age.base()};
424 }
425 }
426 }
427
429}
430
435void AfterLoadVehiclesPhase2(bool part_of_load)
436{
437 for (Vehicle *v : Vehicle::Iterate()) {
438 assert(v->First() != nullptr);
439
440 v->trip_occupancy = CalcPercentVehicleFilled(v, nullptr);
441
442 switch (v->type) {
443 case VehicleType::Train: {
444 Train *t = Train::From(v);
445 if (t->IsFrontEngine() || t->IsFreeWagon()) {
446 t->gcache.last_speed = t->cur_speed; // update displayed train speed
448 }
449 break;
450 }
451
452 case VehicleType::Road: {
454 if (rv->IsFrontEngine()) {
455 rv->gcache.last_speed = rv->cur_speed; // update displayed road vehicle speed
456
457 rv->roadtype = Engine::Get(rv->engine_type)->VehInfo<RoadVehicleInfo>().roadtype;
459 RoadTramType rtt = GetRoadTramType(rv->roadtype);
460 for (RoadVehicle *u = rv; u != nullptr; u = u->Next()) {
461 u->roadtype = rv->roadtype;
462 u->compatible_roadtypes = rv->compatible_roadtypes;
463 if (GetRoadType(u->tile, rtt) == INVALID_ROADTYPE) SlErrorCorrupt("Road vehicle on invalid road type");
464 }
465
467 if (_settings_game.vehicle.roadveh_acceleration_model != AccelerationModel::Original) {
468 rv->CargoChanged();
469 }
470 }
471 break;
472 }
473
476 break;
477
478 default: break;
479 }
480 }
481
482 /* Stop non-front engines */
484 for (Vehicle *v : Vehicle::Iterate()) {
485 if (v->type == VehicleType::Train) {
486 Train *t = Train::From(v);
487 if (!t->IsFrontEngine()) {
489 /* cur_speed is now relevant for non-front parts - nonzero breaks
490 * moving-wagons-inside-depot- and autoreplace- code */
491 t->cur_speed = 0;
492 }
493 }
494 /* trains weren't stopping gradually in old OTTD versions (and TTO/TTD)
495 * other vehicle types didn't have zero speed while stopped (even in 'recent' OTTD versions) */
497 v->cur_speed = 0;
498 }
499 }
500 }
501
502 for (Vehicle *v : Vehicle::Iterate()) {
503 switch (v->type) {
507 v->GetImage(v->direction, EngineImageType::OnMap, &v->sprite_cache.sprite_seq);
508 break;
509
511 if (Aircraft::From(v)->IsNormalAircraft()) {
512 v->GetImage(v->direction, EngineImageType::OnMap, &v->sprite_cache.sprite_seq);
513
514 /* The aircraft's shadow will have the same image as the aircraft, but no colour */
515 Vehicle *shadow = v->Next();
516 if (shadow == nullptr) SlErrorCorrupt("Missing shadow for aircraft");
517
518 shadow->sprite_cache.sprite_seq.CopyWithoutPalette(v->sprite_cache.sprite_seq);
519
520 /* In the case of a helicopter we will update the rotor sprites */
521 if (v->subtype == AIR_HELICOPTER) {
522 Vehicle *rotor = shadow->Next();
523 if (rotor == nullptr) SlErrorCorrupt("Missing rotor for helicopter");
524
526 }
527
529 }
530 break;
531
533 auto *dv = DisasterVehicle::From(v);
534 if (dv->subtype == ST_SMALL_UFO && dv->state != 0) {
535 RoadVehicle *u = RoadVehicle::GetIfValid(v->dest_tile.base());
536 if (u != nullptr && u->IsFrontEngine()) {
537 /* Delete UFO targetting a vehicle which is already a target. */
538 if (u->disaster_vehicle != VehicleID::Invalid() && u->disaster_vehicle != dv->index) {
539 delete v;
540 continue;
541 } else {
542 u->disaster_vehicle = dv->index;
543 }
544 }
545 }
546 break;
547 }
548
549 default: break;
550 }
551
552 if (part_of_load && v->unitnumber != 0) {
553 Company::Get(v->owner)->freeunits[v->type].UseID(v->unitnumber);
554 }
555
556 v->UpdateDeltaXY();
557 v->coord.left = INVALID_COORD;
558 v->sprite_cache.old_coord.left = INVALID_COORD;
559 if (v->type != VehicleType::Effect) v->UpdatePosition();
560 v->UpdateViewport(false);
561 }
562}
563
564bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // From train_cmd.cpp
566
569{
570 /* Vehicle center was moved from 4 units behind the front to half the length
571 * behind the front. Move vehicles so they end up on the same spot. */
572 for (Vehicle *v : Vehicle::Iterate()) {
573 if (v->type == VehicleType::Train && v->IsPrimaryVehicle()) {
574 /* The vehicle center is now more to the front depending on vehicle length,
575 * so we need to move all vehicles forward to cover the difference to the
576 * old center, otherwise wagon spacing in trains would be broken upon load. */
577 for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
578 if (u->track == Track::Depot || u->vehstatus.Test(VehState::Crashed)) continue;
579
580 Train *next = u->Next();
581
582 /* Try to pull the vehicle half its length forward. */
583 int diff = (VEHICLE_LENGTH - u->gcache.cached_veh_length) / 2;
584 int done;
585 for (done = 0; done < diff; done++) {
586 if (!TrainController(u, next, false)) break;
587 }
588
589 if (next != nullptr && done < diff && u->IsFrontEngine()) {
590 /* Pulling the front vehicle forwards failed, we either encountered a dead-end
591 * or a red signal. To fix this, we try to move the whole train the required
592 * space backwards and re-do the fix up of the front vehicle. */
593
594 /* Ignore any signals when backtracking. */
595 TrainForceProceeding old_tfp = u->force_proceed;
596 u->force_proceed = TFP_SIGNAL;
597
598 /* Swap start<>end, start+1<>end-1, ... */
600
601 /* We moved the first vehicle which is now the last. Move it back to the
602 * original position as we will fix up the last vehicle later in the loop. */
603 for (int i = 0; i < done; i++) TrainController(u->Last(), nullptr);
604
605 /* Move the train backwards to get space for the first vehicle. As the stopping
606 * distance from a line end is rounded up, move the train one unit more to cater
607 * for front vehicles with odd lengths. */
608 int moved;
609 for (moved = 0; moved < diff + 1; moved++) {
610 if (!TrainController(u, nullptr, false)) break;
611 }
612
613 /* Swap start<>end, start+1<>end-1, ... again. */
615
616 u->force_proceed = old_tfp;
617
618 /* Tracks are too short to fix the train length. The player has to fix the
619 * train in a depot. Bail out so we don't damage the vehicle chain any more. */
620 if (moved < diff + 1) break;
621
622 /* Re-do the correction for the first vehicle. */
623 for (done = 0; done < diff; done++) TrainController(u, next, false);
624
625 /* We moved one unit more backwards than needed for even-length front vehicles,
626 * try to move that unit forward again. We don't care if this step fails. */
627 TrainController(u, nullptr, false);
628 }
629
630 /* If the next wagon is still in a depot, check if it shouldn't be outside already. */
631 if (next != nullptr && next->track == Track::Depot) {
632 int d = TicksToLeaveDepot(u);
633 if (d <= 0) {
634 /* Next vehicle should have left the depot already, show it and pull forward. */
636 next->track = GetRailDepotTrack(next->tile);
637 for (int i = 0; i >= d; i--) TrainController(next, nullptr);
638 }
639 }
640 }
641
642 /* Update all cached properties after moving the vehicle chain around. */
644 }
645 }
646}
647
648static uint8_t _cargo_periods;
649static StationID _cargo_source;
650static TileIndex _cargo_source_xy;
651static uint16_t _cargo_count;
652static uint16_t _cargo_paid_for;
653static Money _cargo_feeder_share;
654
655class SlVehicleCommon : public DefaultSaveLoadHandler<SlVehicleCommon, Vehicle> {
656public:
657 static inline const SaveLoad description[] = {
659
670
678
683 SaveLoad::Variable<VarFileType::U8>("acceleration", SLE_OBJECT_ADDRESS(Vehicle, acceleration)),
686
689 SaveLoad::Variable<VarFileType::U16>("last_station_visited", SLE_OBJECT_ADDRESS(Vehicle, last_station_visited), SaveLoadVersion::BigMap),
691
704
706 SaveLoad::Variable<VarFileType::U8>("tick_counter", SLE_OBJECT_ADDRESS(Vehicle, tick_counter)),
708
709 SaveLoad::Variable<VarFileType::U8>("cur_implicit_order_index", SLE_OBJECT_ADDRESS(Vehicle, cur_implicit_order_index)),
711
712 /* This next line is for version 4 and prior compatibility.. it temporarily reads
713 type and flags (which were both 4 bits) into type. Later on this is
714 converted correctly */
717
718 /* Orders for version 5 and on */
720 SaveLoad::Variable<VarFileType::U8>("current_order.flags", SLE_OBJECT_ADDRESS(Vehicle, current_order.flags), SaveLoadVersion::BigMap),
722
723 /* Refit in current order */
724 SaveLoad::Variable<VarFileType::U8>("current_order.refit_cargo", SLE_OBJECT_ADDRESS(Vehicle, current_order.refit_cargo), SaveLoadVersion::RefitOrders),
725
726 /* Timetable in current order */
727 SaveLoad::Variable<VarFileType::U16>("current_order.wait_time", SLE_OBJECT_ADDRESS(Vehicle, current_order.wait_time), SaveLoadVersion::Timetables),
728 SaveLoad::Variable<VarFileType::U16>("current_order.travel_time", SLE_OBJECT_ADDRESS(Vehicle, current_order.travel_time), SaveLoadVersion::Timetables),
732
736
743 SaveLoad::Variable<VarFileType::I32>("date_of_last_service", SLE_OBJECT_ADDRESS(Vehicle, date_of_last_service), SaveLoadVersion::BigDates),
744 SaveLoad::Variable<VarFileType::I32>("date_of_last_service_newgrf", SLE_OBJECT_ADDRESS(Vehicle, date_of_last_service_newgrf), SaveLoadVersion::NewGRFLastService),
749 SaveLoad::Variable<VarFileType::U16>("reliability_spd_dec", SLE_OBJECT_ADDRESS(Vehicle, reliability_spd_dec)),
750 SaveLoad::Variable<VarFileType::U8>("breakdown_ctr", SLE_OBJECT_ADDRESS(Vehicle, breakdown_ctr)),
751 SaveLoad::Variable<VarFileType::U8>("breakdown_delay", SLE_OBJECT_ADDRESS(Vehicle, breakdown_delay)),
752 SaveLoad::Variable<VarFileType::U8>("breakdowns_since_last_service", SLE_OBJECT_ADDRESS(Vehicle, breakdowns_since_last_service)),
753 SaveLoad::Variable<VarFileType::U8>("breakdown_chance", SLE_OBJECT_ADDRESS(Vehicle, breakdown_chance)),
756
757 SaveLoad::Variable<VarFileType::U16>("load_unload_ticks", SLE_OBJECT_ADDRESS(Vehicle, load_unload_ticks)),
761
770
774
777
782
783 SaveLoad::Variable<VarFileType::U64>("depot_unbunching_last_departure", SLE_OBJECT_ADDRESS(Vehicle, depot_unbunching_last_departure), SaveLoadVersion::DepotUnbunching),
784 SaveLoad::Variable<VarFileType::U64>("depot_unbunching_next_departure", SLE_OBJECT_ADDRESS(Vehicle, depot_unbunching_next_departure), SaveLoadVersion::DepotUnbunching),
786 };
787
788 static inline const SaveLoadCompatTable compat_description = _vehicle_common_sl_compat;
789
790 void Save(Vehicle *v) const override
791 {
792 SlObject(v, this->GetDescription());
793 }
794
795 void Load(Vehicle *v) const override
796 {
797 SlObject(v, this->GetLoadDescription());
798 }
799
800 void FixPointers(Vehicle *v) const override
801 {
802 SlObject(v, this->GetDescription());
803 }
804};
805
806class SlVehicleTrain : public DefaultSaveLoadHandler<SlVehicleTrain, Vehicle> {
807public:
808 static inline const SaveLoad description[] = {
810 SaveLoad::Variable<VarFileType::U16>("crash_anim_pos", SLE_OBJECT_ADDRESS(Train, crash_anim_pos)),
811 SaveLoad::Variable<VarFileType::U8>("force_proceed", SLE_OBJECT_ADDRESS(Train, force_proceed)),
813
818 };
819 static inline const SaveLoadCompatTable compat_description = _vehicle_train_sl_compat;
820
821 void Save(Vehicle *v) const override
822 {
823 if (v->type != VehicleType::Train) return;
824 SlObject(v, this->GetDescription());
825 }
826
827 void Load(Vehicle *v) const override
828 {
829 if (v->type != VehicleType::Train) return;
830 SlObject(v, this->GetLoadDescription());
831 }
832
833 void FixPointers(Vehicle *v) const override
834 {
835 if (v->type != VehicleType::Train) return;
836 SlObject(v, this->GetDescription());
837 }
838};
839
840class SlVehicleRoadVehPath : public VectorSaveLoadHandler<SlVehicleRoadVehPath, RoadVehicle, RoadVehPathElement> {
841public:
842 static inline const SaveLoad description[] = {
845 };
846 static inline const SaveLoadCompatTable compat_description = {};
847
848 std::vector<RoadVehPathElement> &GetVector(RoadVehicle *rv) const override { return rv->path; }
849};
850
851class SlVehicleRoadVeh : public DefaultSaveLoadHandler<SlVehicleRoadVeh, Vehicle> {
852public:
855 static inline std::vector<Trackdir> rv_path_td;
856 static inline std::vector<TileIndex> rv_path_tile;
858
859 static inline const SaveLoad description[] = {
865 SaveLoad::Variable<VarFileType::U8>("overtaking_ctr", SLE_OBJECT_ADDRESS(RoadVehicle, overtaking_ctr)),
872 };
873 static inline const SaveLoadCompatTable compat_description = _vehicle_roadveh_sl_compat;
874
875 static void ConvertPathCache(RoadVehicle &rv)
876 {
877 /* The two vectors should be the same size, but if not we can just ignore the cache and not cause more issues. */
878 if (rv_path_td.size() != rv_path_tile.size()) {
879 Debug(Facility::Sl, Severity::Error, "Found RoadVehicle {} with invalid path cache, ignoring.", rv.index);
880 return;
881 }
882 size_t n = std::min(rv_path_td.size(), rv_path_tile.size());
883 if (n == 0) return;
884
885 rv.path.reserve(n);
886 for (size_t c = 0; c < n; ++c) {
887 rv.path.emplace_back(rv_path_td[c], rv_path_tile[c]);
888 }
889
890 /* Path cache is now taken from back instead of front, so needs reversing. */
891 std::reverse(std::begin(rv.path), std::end(rv.path));
892 }
893
894 void Save(Vehicle *v) const override
895 {
896 if (v->type != VehicleType::Road) return;
897 SlObject(v, this->GetDescription());
898 }
899
900 void Load(Vehicle *v) const override
901 {
902 if (v->type != VehicleType::Road) return;
903 SlObject(v, this->GetLoadDescription());
905 ConvertPathCache(*static_cast<RoadVehicle *>(v));
906 }
907 }
908
909 void FixPointers(Vehicle *v) const override
910 {
911 if (v->type != VehicleType::Road) return;
912 SlObject(v, this->GetDescription());
913 }
914};
915
916class SlVehicleShipPath : public VectorSaveLoadHandler<SlVehicleShipPath, Ship, ShipPathElement> {
917public:
918 static inline const SaveLoad description[] = {
920 };
921 static inline const SaveLoadCompatTable compat_description = {};
922
923 std::vector<ShipPathElement> &GetVector(Ship *s) const override { return s->path; }
924};
925
926class SlVehicleShip : public DefaultSaveLoadHandler<SlVehicleShip, Vehicle> {
927public:
928 static inline std::vector<Trackdir> ship_path_td;
929
930 static inline const SaveLoad description[] = {
937 };
938 static inline const SaveLoadCompatTable compat_description = _vehicle_ship_sl_compat;
939
940 void Save(Vehicle *v) const override
941 {
942 if (v->type != VehicleType::Ship) return;
943 SlObject(v, this->GetDescription());
944 }
945
946 void Load(Vehicle *v) const override
947 {
948 if (v->type != VehicleType::Ship) return;
949 SlObject(v, this->GetLoadDescription());
950
952 /* Path cache is now taken from back instead of front, so needs reversing. */
953 Ship *s = static_cast<Ship *>(v);
954 std::transform(std::rbegin(ship_path_td), std::rend(ship_path_td), std::back_inserter(s->path), [](Trackdir trackdir) { return trackdir; });
955 }
956 }
957
958 void FixPointers(Vehicle *v) const override
959 {
960 if (v->type != VehicleType::Ship) return;
961 SlObject(v, this->GetDescription());
962 }
963};
964
965class SlVehicleAircraft : public DefaultSaveLoadHandler<SlVehicleAircraft, Vehicle> {
966public:
967 static inline const SaveLoad description[] = {
969 SaveLoad::Variable<VarFileType::U16>("crashed_counter", SLE_OBJECT_ADDRESS(Aircraft, crashed_counter)),
971
974
976
980
983 };
984 static inline const SaveLoadCompatTable compat_description = _vehicle_aircraft_sl_compat;
985
986 void Save(Vehicle *v) const override
987 {
988 if (v->type != VehicleType::Aircraft) return;
989 SlObject(v, this->GetDescription());
990 }
991
992 void Load(Vehicle *v) const override
993 {
994 if (v->type != VehicleType::Aircraft) return;
995 SlObject(v, this->GetLoadDescription());
996 }
997
998 void FixPointers(Vehicle *v) const override
999 {
1000 if (v->type != VehicleType::Aircraft) return;
1001 SlObject(v, this->GetDescription());
1002 }
1003};
1004
1005class SlVehicleEffect : public DefaultSaveLoadHandler<SlVehicleEffect, Vehicle> {
1006public:
1007 static inline const SaveLoad description[] = {
1009
1012
1019
1020 SaveLoad::Variable<VarFileType::U16>("sprite_cache.sprite_seq.seq[0].sprite", SLE_OBJECT_ADDRESS(Vehicle, sprite_cache.sprite_seq.seq[0].sprite)),
1023
1024 SaveLoad::Variable<VarFileType::U16>("animation_state", SLE_OBJECT_ADDRESS(EffectVehicle, animation_state)),
1025 SaveLoad::Variable<VarFileType::U8>("animation_substate", SLE_OBJECT_ADDRESS(EffectVehicle, animation_substate)),
1026
1028 };
1029 static inline const SaveLoadCompatTable compat_description = _vehicle_effect_sl_compat;
1030
1031 void Save(Vehicle *v) const override
1032 {
1033 if (v->type != VehicleType::Effect) return;
1034 SlObject(v, this->GetDescription());
1035 }
1036
1037 void Load(Vehicle *v) const override
1038 {
1039 if (v->type != VehicleType::Effect) return;
1040 SlObject(v, this->GetLoadDescription());
1041 }
1042
1043 void FixPointers(Vehicle *v) const override
1044 {
1045 if (v->type != VehicleType::Effect) return;
1046 SlObject(v, this->GetDescription());
1047 }
1048};
1049
1050class SlVehicleDisaster : public DefaultSaveLoadHandler<SlVehicleDisaster, Vehicle> {
1051public:
1052 static inline const SaveLoad description[] = {
1054
1060
1068
1074
1075 SaveLoad::Variable<VarFileType::U16>("sprite_cache.sprite_seq.seq[0].sprite", SLE_OBJECT_ADDRESS(Vehicle, sprite_cache.sprite_seq.seq[0].sprite)),
1078 SaveLoad::Variable<VarFileType::U8>("tick_counter", SLE_OBJECT_ADDRESS(Vehicle, tick_counter)),
1079
1085 };
1086
1087 static inline const SaveLoadCompatTable compat_description = _vehicle_disaster_sl_compat;
1088
1089 void Save(Vehicle *v) const override
1090 {
1091 if (v->type != VehicleType::Disaster) return;
1092 SlObject(v, this->GetDescription());
1093 }
1094
1095 void Load(Vehicle *v) const override
1096 {
1097 if (v->type != VehicleType::Disaster) return;
1098 SlObject(v, this->GetLoadDescription());
1099 }
1100
1101 void FixPointers(Vehicle *v) const override
1102 {
1103 if (v->type != VehicleType::Disaster) return;
1104 SlObject(v, this->GetDescription());
1105 }
1106};
1107
1108static const SaveLoad _vehicle_desc[] = {
1116};
1117
1118struct VEHSChunkHandler : ChunkHandler {
1119 VEHSChunkHandler() : ChunkHandler("VEHS", ChunkType::SparseTable) {}
1120
1121 void Save() const override
1122 {
1123 SlTableHeader(_vehicle_desc);
1124
1125 /* Write the vehicles */
1126 for (Vehicle *v : Vehicle::Iterate()) {
1127 SlSetArrayIndex(v->index);
1128 SlObject(v, _vehicle_desc);
1129 }
1130 }
1131
1132 void Load() const override
1133 {
1134 const std::vector<SaveLoad> slt = SlCompatTableHeader(_vehicle_desc, _vehicle_sl_compat);
1135
1136 int index;
1137
1138 _cargo_count = 0;
1139
1140 while ((index = SlIterateArray()) != -1) {
1141 Vehicle *v;
1143
1144 switch (vtype) {
1145 case VehicleType::Train: v = Train::CreateAtIndex(VehicleID(index)); break;
1147 case VehicleType::Ship: v = Ship::CreateAtIndex(VehicleID(index)); break;
1151 case VehicleType::Invalid: // Savegame shouldn't contain invalid vehicles
1152 default: SlErrorCorrupt("Invalid vehicle type");
1153 }
1154
1155 SlObject(v, slt);
1156
1157 if (_cargo_count != 0 && IsCompanyBuildableVehicleType(v) && CargoPacket::CanAllocateItem()) {
1158 /* Don't construct the packet with station here, because that'll fail with old savegames */
1159 CargoPacket *cp = CargoPacket::Create(_cargo_count, _cargo_periods, _cargo_source, _cargo_source_xy, _cargo_feeder_share);
1160 v->cargo.Append(cp);
1161 }
1162
1163 /* Old savegames used 'last_station_visited = 0xFF' */
1165 v->last_station_visited = StationID::Invalid();
1166 }
1167
1169
1171 /* Convert the current_order.type (which is a mix of type and flags, because
1172 * in those versions, they both were 4 bits big) to type and flags */
1173 v->current_order.flags = GB(v->current_order.type, 4, 4);
1174 v->current_order.type &= 0x0F;
1175 }
1176
1177 /* Advanced vehicle lists got added */
1179 }
1180 }
1181
1182 void FixPointers() const override
1183 {
1184 for (Vehicle *v : Vehicle::Iterate()) {
1185 SlObject(v, _vehicle_desc);
1186 }
1187 }
1188};
1189
1190static const VEHSChunkHandler VEHS;
1191static const ChunkHandlerRef veh_chunk_handlers[] = {
1192 VEHS,
1193};
1194
1195extern const ChunkHandlerTable _veh_chunk_handlers(veh_chunk_handlers);
Base for aircraft.
void GetAircraftFlightLevelBounds(const Vehicle *v, int *min, int *max)
Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular vehicle for normal flight si...
void AircraftNextAirportPos_and_Order(Aircraft *v)
Set the right pos when heading to other airports after takeoff.
void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
Aircraft is about to leave the hangar.
void SetAircraftPosition(Aircraft *v, int x, int y, int z)
Set aircraft position.
@ AIR_HELICOPTER
an helicopter
Definition aircraft.h:29
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
@ HANGAR
Heading for hangar.
Definition airport.h:65
@ FLYING
Vehicle is flying in the air.
Definition airport.h:78
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
Default handler for saving/loading an object to/from disk.
Definition saveload.h:585
SaveLoadTable GetDescription() const override
Definition saveload.h:587
static Pool::IterateWrapperFiltered< Engine, EngineTypeFilter > IterateType(VehicleType vt, size_t from=0)
Returns an iterable ensemble of all valid engines of the given type.
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition road.h:98
SaveLoadTable GetLoadDescription() const
Get the description for how to load the chunk.
void Load(Vehicle *v) const override
Load the object from disk.
void FixPointers(Vehicle *v) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Save(Vehicle *v) const override
Save the object to disk.
void Save(Vehicle *v) const override
Save the object to disk.
void FixPointers(Vehicle *v) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Load(Vehicle *v) const override
Load the object from disk.
void Save(Vehicle *v) const override
Save the object to disk.
void Load(Vehicle *v) const override
Load the object from disk.
void FixPointers(Vehicle *v) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void FixPointers(Vehicle *v) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Save(Vehicle *v) const override
Save the object to disk.
void Load(Vehicle *v) const override
Load the object from disk.
std::vector< RoadVehPathElement > & GetVector(RoadVehicle *rv) const override
Get instance of vector to load/save.
void Load(Vehicle *v) const override
Load the object from disk.
void FixPointers(Vehicle *v) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
static std::vector< TileIndex > rv_path_tile
static std::vector< Trackdir > rv_path_td
void Save(Vehicle *v) const override
Save the object to disk.
std::vector< ShipPathElement > & GetVector(Ship *s) const override
Get instance of vector to load/save.
void Load(Vehicle *v) const override
Load the object from disk.
void FixPointers(Vehicle *v) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Save(Vehicle *v) const override
Save the object to disk.
void FixPointers(Vehicle *v) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Load(Vehicle *v) const override
Load the object from disk.
void Save(Vehicle *v) const override
Save the object to disk.
StrongType::Typedef< int32_t, DateTag< struct Economy >, StrongType::Compare, StrongType::Integer > Date
Default handler for saving/loading a vector to/from disk.
Definition saveload.h:1340
void Append(CargoPacket *cp, MoveToAction action=MoveToAction::Keep)
Appends the given cargo packet.
Definition of stuff that is very close to a company, like the company struct itself.
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
Functions related to companies.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Sl
Saveload message facility.
Definition debug_type.h:39
@ Error
Error, but we are recovering.
Definition debug_type.h:16
All disaster vehicles.
@ ST_SMALL_UFO
Small UFO, tries to find a road vehicle to destroy.
Base classes related to the economy.
Base class for all effect vehicles.
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
Definition engine_type.h:25
@ Multihead
indicates a combination of two locomotives
Definition engine_type.h:32
@ Wagon
simple wagon, not motorized
Definition engine_type.h:33
static constexpr GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition group_type.h:18
uint8_t _age_cargo_skip_counter
Skip aging of cargo? Used before savegame version 162.
Definition misc_sl.cpp:84
OldOrderSaveLoadItem * GetOldOrder(size_t pool_index)
Get a pointer to an old order with the given reference index.
Definition order_sl.cpp:126
int TicksToLeaveDepot(const Train *v)
Compute number of ticks when next wagon will leave a depot.
Track GetRailDepotTrack(Tile t)
Returns the track of a depot, ignoring direction.
Definition rail_map.h:182
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:217
RoadType GetRoadType(Tile t, RoadTramType rtt)
Get the road type for the given RoadTramType.
Definition road_map.h:175
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition road_type.h:29
RoadTramType
The different types of road type.
Definition road_type.h:38
Road vehicle states.
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
A number of safeguards to prevent using unsafe methods.
std::vector< SaveLoad > SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
Load a table header in a savegame compatible way.
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition saveload.cpp:748
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition saveload.cpp:372
uint8_t SlReadByte()
Wrapper for reading a byte from the buffer.
Definition saveload.cpp:413
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
Functions/types related to saving and loading games.
#define SLE_OBJECT_ADDRESS(base, variable)
Macro to be able to pass the variable type and construct the SaveLoad::AddressFunction given a base c...
Definition saveload.h:753
#define SLE_GLOBAL_ADDRESS(variable)
Macro to be able to pass the variable type and construct the SaveLoad::AddressFunction given a global...
Definition saveload.h:760
std::reference_wrapper< const ChunkHandler > ChunkHandlerRef
A reference to ChunkHandler.
Definition saveload.h:512
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition saveload.h:515
std::span< const struct SaveLoadCompat > SaveLoadCompatTable
A table of SaveLoadCompat entries.
Definition saveload.h:518
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1225
@ LastLoadingTick
Saveload version: 301, GitHub pull request: 9693 Store tick of last loading for vehicles.
Definition saveload.h:346
@ BigDates
Saveload version: 31, SVN revision: 5999 Change date from 1920 - 2090 to 0 - 5 000 000.
Definition saveload.h:86
@ FractionProfitRunningTicks
Saveload version: 88, SVN revision: 12134 Store vehicle profits as a (fixed point) fraction,...
Definition saveload.h:154
@ VehicleEconomyAge
Saveload version: 334, GitHub pull request: 12141, release: 14.0 Add vehicle age in economy year,...
Definition saveload.h:385
@ GoalProgressPlaneAcceleration
Saveload version: 182, SVN revision: 25115, r25259, r25296 Goal status and plane acceleration fixes.
Definition saveload.h:267
@ LiveryRefit
Saveload version: 35, SVN revision: 6602 NewGRF livery refits.
Definition saveload.h:91
@ CountPaidForCargo
Saveload version: 45, SVN revision: 8501 Count the amount of cargo that was paid for.
Definition saveload.h:103
@ UnifyCurrency
Saveload version: 65, SVN revision: 10210 Make all variables related to currency 64 bits.
Definition saveload.h:127
@ DisasterVehState
Saveload version: 312, GitHub pull request: 10798 Explicit storage of disaster vehicle state.
Definition saveload.h:359
@ CargoReservation
Saveload version: 181, SVN revision: 25012 Persist the reservation of cargo for vehicles instead of ...
Definition saveload.h:266
@ LargerUnitNumber
Saveload version: 8.0, SVN revision: 1786 Increase size of (vehicle) unit numbers.
Definition saveload.h:55
@ ReplaceCustomNameArray
Saveload version: 84, SVN revision: 11822 Replace single fixed size array of custom names,...
Definition saveload.h:149
@ OrderList
Saveload version: 105, SVN revision: 14803 Create separate order list objects for maintaining orders...
Definition saveload.h:175
@ PathCacheFormat
Saveload version: 346, GitHub pull request: 12345 Vehicle path cache format changed.
Definition saveload.h:400
@ VehicleCurrencyStationChanges
Saveload version: 2.0, release: 0.3.0 Adding vehicle state, larger currency size for statistics,...
Definition saveload.h:39
@ ShipPathCache
Saveload version: 203, GitHub pull request: 7072 Add path cache for ships.
Definition saveload.h:292
@ TrackRealAndAutoOrders
Saveload version: 158, SVN revision: 21933 Track which real and auto order is the current order.
Definition saveload.h:238
@ VehicleCentreAndZPos
Saveload version: 164, SVN revision: 23290 Vehicle centres are not fixed at 4/8 of the vehicle; chan...
Definition saveload.h:245
@ BigMap
Saveload version: 5.0, SVN revision: 1429 Making maps a different size than 256x256.
Definition saveload.h:49
@ LargerCargoSource
Saveload version: 7.0, SVN revision: 1770 With more stations, the size of the cargo source needed to...
Definition saveload.h:54
@ NewGRFLastService
Saveload version: 317, GitHub pull request: 11124 Added stable date_of_last_service to avoid NewGRF ...
Definition saveload.h:365
@ MoreCargoPackets
Saveload version: 69, SVN revision: 10319 Allow more than ~65k cargo packets.
Definition saveload.h:131
@ LinkgraphLocationDisasterStore
Saveload version: 191, SVN revision: 26636, 26646 Fix disaster vehicle storage, Linkgraph - store lo...
Definition saveload.h:278
@ RoadvehPathCache
Saveload version: 211, GitHub pull request: 7261 Add path cache for road vehicles.
Definition saveload.h:302
@ RefitOrders
Saveload version: 36, SVN revision: 6624 Vehicles can be refitted as part of an order.
Definition saveload.h:92
@ UnifyGroundVehicles
Saveload version: 157, SVN revision: 21862 Unify the way ground vehicles are handled (articulated pa...
Definition saveload.h:237
@ CargoSourceTile
Saveload version: 44, SVN revision: 8144 Store the source tile of the cargo, so accurate payment can...
Definition saveload.h:101
@ VehMotionCounter
Saveload version: 288, GitHub pull request: 8591 Desync safe motion counter.
Definition saveload.h:330
@ TimetableStartTicks
Saveload version: 321, GitHub pull request: 11468 Convert timetable start from a date to ticks.
Definition saveload.h:370
@ CurrentOrderMaxSpeed
Saveload version: 174, SVN revision: 23973, release: 1.2.x Save maximum speed of current order.
Definition saveload.h:257
@ MultipleRoadStops
Saveload version: 6.0, SVN revision: 1721 Multi tile road stops, and some map size related fixes.
Definition saveload.h:52
@ VehicleGroups
Saveload version: 60, SVN revision: 9874 Arbitrary grouping, by the player, of vehicles.
Definition saveload.h:121
@ ServiceIntervalPercent
Saveload version: 180, SVN revision: 24998, release: 1.3.x Service interval in percent or days store...
Definition saveload.h:265
@ NewGRFCustomCargoAging
Saveload version: 162, SVN revision: 22713 NewGRF influence on aging of cargo in vehicles.
Definition saveload.h:243
@ DisallowRoadReconstruction
Saveload version: 160, SVN revision: 21974, release: 1.1.x Setting to disallow road reconstruction.
Definition saveload.h:241
@ TimetableTicksType
Saveload version: 323, GitHub pull request: 11435 Convert timetable current order time to ticks.
Definition saveload.h:372
@ NewGRFAircraftRange
Saveload version: 167, SVN revision: 23504 NewGRF provided maximum aircraft range.
Definition saveload.h:249
@ ExtendVehicleRandom
Saveload version: 310, GitHub pull request: 10701 Extend vehicle random bits.
Definition saveload.h:357
@ MinVersion
First savegame version.
Definition saveload.h:36
@ SplitLoadWaitCounters
Saveload version: 136, SVN revision: 18764 Split counters for (un)loading and signal waiting/turning...
Definition saveload.h:212
@ SplitHQ
Saveload version: 112, SVN revision: 15290 Split the behaviour of headquarters from the other unmova...
Definition saveload.h:183
@ FeederShare
Saveload version: 51, SVN revision: 8978 Rewrite of transfers to retain knowledge about the already ...
Definition saveload.h:110
@ DepotUnbunching
Saveload version: 331, GitHub pull request: 11945 Allow unbunching shared order vehicles at a depot.
Definition saveload.h:382
@ ShipRotation
Saveload version: 204, GitHub pull request: 7065 Add extra rotation stages for ships.
Definition saveload.h:293
@ Timetables
Saveload version: 67, SVN revision: 10236 Introduce timetables for vehicles.
Definition saveload.h:129
@ RvRealisticAcceleration
Saveload version: 139, SVN revision: 19346 Realistic acceleration of road vehicles.
Definition saveload.h:215
@ Yapp
Saveload version: 100, SVN revision: 13952 New version of path based signals.
Definition saveload.h:169
@ CargoPackets
Saveload version: 68, SVN revision: 10266 Account for individual units of cargo, i....
Definition saveload.h:130
@ MaxBridgeMapHeight
Saveload version: 194, SVN revision: 26881, release: 1.5 Setting for maximum bridge and map height.
Definition saveload.h:281
@ TimetableStart
Saveload version: 129, SVN revision: 18292 Allow setting the start date of a timetable.
Definition saveload.h:203
@ GradualLoading
Saveload version: 40, SVN revision: 7326 Gradual (un)loading of cargo.
Definition saveload.h:97
@ SparseTable
A SparseArray with a header describing the elements.
Definition saveload.h:450
Functions/types related to errors from savegames.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
Base for ships.
Base classes/functions for stations.
Definition of base types and functions in a cross-platform compatible way.
@ AllowControlCode
Allow the special control codes.
Definition string_type.h:47
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:75
VehicleType type
Type of vehicle.
Container for cargo from the same location and time.
Definition cargopacket.h:40
ChunkHandler(ChunkId id, ChunkType type)
Create this ChunkHandler.
Definition saveload.h:469
CompanySettings settings
settings specific for each company
VehicleDefaultSettings vehicle
default settings for vehicles
Disasters, like submarines, skyrangers and their shadows, belong to this class.
A special vehicle is one of the following:
Position information of a vehicle after it moved.
int y
x and y position of the vehicle after moving
uint16_t last_speed
The last speed we did display, so we only have to redraw when this changes.
GroundVehicleCache gcache
Cache of often calculated values.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
void ClearEngine()
Clear engine status.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Compatibility struct to allow saveload of pool-based orders.
Definition order_base.h:367
std::vector< Order > orders
Orders of the order list.
Definition order_base.h:394
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
uint8_t type
The type of order + non-stop flags.
Definition order_base.h:47
uint8_t flags
Load/unload types, depot order/action types.
Definition order_base.h:48
static Pool::IterateWrapper< Vehicle > Iterate(size_t from=0)
static T * CreateAtIndex(VehicleID index, Targs &&... args)
static Company * Get(auto index)
static Vehicle * GetIfValid(auto index)
Information about a rail vehicle.
Definition engine_type.h:73
RailVehicleType railveh_type
Type of rail vehicle.
Definition engine_type.h:75
Element of the RoadVehPathCache.
Definition roadveh.h:92
Information about a road vehicle.
Buses, trucks and trams belong to this class.
Definition roadveh.h:105
RoadTypes compatible_roadtypes
NOSAVE: Roadtypes this consist is powered on.
Definition roadveh.h:117
RoadVehPathCache path
Cached path.
Definition roadveh.h:106
RoadType roadtype
NOSAVE: Roadtype of this vehicle.
Definition roadveh.h:115
VehicleID disaster_vehicle
NOSAVE: Disaster vehicle targetting this vehicle.
Definition roadveh.h:116
SaveLoad type struct.
Definition saveload.h:763
static SaveLoad StructList(std::string name, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a list of structs, optionally in some savegame versions.
Definition saveload.h:1102
static SaveLoad SaveByte(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a byte variable in some savegame versions that is not automatically read by the SaveLoad c...
Definition saveload.h:1124
static SaveLoad Variable(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of a variable in some savegame versions.
Definition saveload.h:925
static SaveLoad ReferenceList(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a list of references to pool elements in some savegame versions.
Definition saveload.h:1077
static SaveLoad Array(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of an array in some savegame versions.
Definition saveload.h:1025
static SaveLoad Vector(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a vector in some savegame versions.
Definition saveload.h:1052
static SaveLoad Reference(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a reference to a pool element in some savegame versions.
Definition saveload.h:950
static SaveLoad Struct(std::string name, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a structs, optionally in some savegame versions.
Definition saveload.h:1000
static SaveLoad String(std::string name, AddressFunction< T > address_func, StringValidationSettings string_validation_settings={}, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of a string in some savegame versions.
Definition saveload.h:976
Element of the ShipPathCache.
Definition ship.h:20
All ships have this type.
Definition ship.h:39
ShipPathCache path
Cached path.
Definition ship.h:40
void UpdateCache()
Update the caches of this ship.
Definition ship_cmd.cpp:236
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
T * Next() const
Get next vehicle in the chain.
static Train * From(Vehicle *v)
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
Station data structure.
'Train' is either a loco or a wagon.
Definition train.h:97
Train * other_multiheaded_part
Link between the two ends of a multiheaded engine.
Definition train.h:105
TrackBits track
On which track the train currently is.
Definition train.h:110
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
void FixPointers() const override
Fix the pointers.
void Load() const override
Load the chunk.
void Save() const override
Save the chunk.
bool servint_ispercent
service intervals are in percents
void CopyWithoutPalette(const VehicleSpriteSeq &src)
Copy data from another sprite sequence, while dropping all recolouring information.
Vehicle data structure.
CargoPayment * cargo_payment
The cargo payment we're currently in.
EngineID engine_type
The type of engine used for this vehicle.
VehicleCargoList cargo
The cargo this vehicle is carrying.
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
GroupID group_id
Index of group Pool array.
VehStates vehstatus
Status.
Order current_order
The current order (+ status, like: loading).
Vehicle * Next() const
Get the next vehicle of this vehicle.
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint16_t cur_speed
current speed
bool IsFrontEngine() const
Check if the vehicle is a front engine.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
TileIndex tile
Current tile index.
StationID last_station_visited
The last station we stopped at.
Vehicle * next_shared
pointer to the next vehicle that shares the order
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
Functions related to time tabling.
TimerGameTick::TickCounter GetStartTickFromDate(TimerGameEconomy::Date start_date)
Get the TimerGameTick::TickCounter tick of a given date.
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:63
@ Depot
Special flag indicating a vehicle is inside a depot.
Definition track_type.h:30
Base for the train class.
static constexpr ConsistChangeFlags CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
Definition train.h:53
static constexpr ConsistChangeFlags CCF_SAVELOAD
Valid changes when loading a savegame. (Everything that is not stored in the save....
Definition train.h:58
TrainForceProceeding
Modes for ignoring signals.
Definition train.h:39
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
Definition train.h:42
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition vehicle.cpp:1804
uint8_t CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
Definition vehicle.cpp:1505
@ Crashed
Vehicle is crashed.
@ Hidden
Vehicle is not visible.
@ Stopped
Vehicle is stopped by the player.
static const int32_t INVALID_COORD
Sentinel for an invalid coordinate.
Functions related to vehicles.
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
void AfterLoadVehiclesPhase1(bool part_of_load)
Called after load for phase 1 of vehicle initialisation.
void FixupTrainLengths()
Fixup old train spacing.
void UpdateOldAircraft()
need to be called to load aircraft from old version
void ConvertOldMultiheadToNew()
Converts all trains to the new subtype format introduced in savegame 16.2 It also links multiheaded e...
void ReverseTrainSwapVehicles(Train *v)
Swap vehicles in chain starting from v, and reverse their direction.
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
void ConnectMultiheadedTrains()
Link front and rear multiheaded engines to each other This is done when loading a savegame.
void AfterLoadVehiclesPhase2(bool part_of_load)
Called after load for phase 2 of vehicle initialisation.
static void CheckValidVehicles()
Check all vehicles to ensure their engine type is valid for the currently loaded NewGRFs (that includ...
Loading of vehicle chunks before table headers were added.
const SaveLoadCompat _vehicle_train_sl_compat[]
Original field order for SlVehicleTrain.
const SaveLoadCompat _vehicle_disaster_sl_compat[]
Original field order for SlVehicleDisaster.
const SaveLoadCompat _vehicle_effect_sl_compat[]
Original field order for SlVehicleEffect.
const SaveLoadCompat _vehicle_ship_sl_compat[]
Original field order for SlVehicleShip.
const SaveLoadCompat _vehicle_sl_compat[]
Original field order for vehicle_desc.
const SaveLoadCompat _vehicle_roadveh_sl_compat[]
Original field order for SlVehicleRoadVeh.
const SaveLoadCompat _vehicle_common_sl_compat[]
Original field order for SlVehicleCommon.
const SaveLoadCompat _vehicle_aircraft_sl_compat[]
Original field order for SlVehicleAircraft.
@ OnMap
Vehicle drawn in viewport.
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ Invalid
Non-existing type of vehicle.
@ Effect
Effect vehicle type (smoke, explosions, sparks, bubbles).
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Disaster
Disaster vehicle type.
@ Train
Train vehicle type.
@ Original
Original acceleration model.
EnumIndexArray< T, VehicleType, Tend > VehicleTypeIndexArray
Array with VehicleType as index.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.