OpenTTD Source 20260711-master-g3fb3006dff
misc_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"
14
17#include "../zoom_func.h"
18#include "../window_gui.h"
19#include "../window_func.h"
20#include "../viewport_func.h"
21#include "../gfx_func.h"
23#include "../fios.h"
24#include "../timer/timer.h"
26
27#include "../safeguards.h"
28
29extern TileIndex _cur_tileloop_tile;
30extern uint16_t _disaster_delay;
31extern uint8_t _trees_tick_ctr;
32
39
40void SaveViewportBeforeSaveGame()
41{
42 /* Don't use GetMainWindow() in case the window does not exist. */
43 const Window *w = FindWindowById(WindowClass::MainWindow, 0);
44 if (w == nullptr || w->viewport == nullptr) {
45 /* Ensure saved position is clearly invalid. */
46 _saved_scrollpos_x = INT_MAX;
47 _saved_scrollpos_y = INT_MAX;
49 } else {
50 _saved_scrollpos_x = w->viewport->scrollpos_x;
51 _saved_scrollpos_y = w->viewport->scrollpos_y;
53 }
54}
55
56void ResetViewportAfterLoadGame()
57{
58 if (_saved_scrollpos_x == INT_MAX && _saved_scrollpos_y == INT_MAX) return;
59
60 Window *w = GetMainWindow();
61
62 w->viewport->scrollpos_x = _saved_scrollpos_x;
63 w->viewport->scrollpos_y = _saved_scrollpos_y;
64 w->viewport->dest_scrollpos_x = _saved_scrollpos_x;
65 w->viewport->dest_scrollpos_y = _saved_scrollpos_y;
66
67 Viewport &vp = *w->viewport;
71
72 /* If zoom_max is ZoomLevel::Min then the setting has not been loaded yet, therefore all levels are allowed. */
73 if (_settings_client.gui.zoom_max != ZoomLevel::Min) {
74 /* Ensure zoom level is allowed */
75 while (vp.zoom < _settings_client.gui.zoom_min) DoZoomInOutWindow(ZOOM_OUT, w);
76 while (vp.zoom > _settings_client.gui.zoom_max) DoZoomInOutWindow(ZOOM_IN, w);
77 }
78
79 DoZoomInOutWindow(ZOOM_NONE, w); // update button status
81}
82
85
86static const SaveLoad _date_desc[] = {
99 SLEG_VAR("next_disaster_start", _disaster_delay, VarTypes::U16),
100 SLEG_VAR("random_state[0]", _random.state[0], VarTypes::U32),
101 SLEG_VAR("random_state[1]", _random.state[1], VarTypes::U32),
103 SLEG_VAR("trees_tick_counter", _trees_tick_ctr, VarTypes::U8),
106 /* For older savegames, we load the current value as the "period"; afterload will set the "fired" and "elapsed". */
112};
113
114static const SaveLoad _date_check_desc[] = {
117};
118
123struct DATEChunkHandler : ChunkHandler {
124 DATEChunkHandler() : ChunkHandler('DATE', ChunkType::Table) {}
125
126 void Save() const override
127 {
128 SlTableHeader(_date_desc);
129
130 SlSetArrayIndex(0);
131 SlGlobList(_date_desc);
132 }
133
134 void LoadCommon(const SaveLoadTable &slt, const SaveLoadCompatTable &slct) const
135 {
136 const std::vector<SaveLoad> oslt = SlCompatTableHeader(slt, slct);
137
139 SlGlobList(oslt);
141 }
142
143 void Load() const override
144 {
145 this->LoadCommon(_date_desc, _date_sl_compat);
146 }
147
148
149 void LoadCheck(size_t) const override
150 {
151 this->LoadCommon(_date_check_desc, _date_check_sl_compat);
152
155 }
156 }
157};
158
159static const SaveLoad _view_desc[] = {
165};
166
167struct VIEWChunkHandler : ChunkHandler {
168 VIEWChunkHandler() : ChunkHandler('VIEW', ChunkType::Table) {}
169
170 void Save() const override
171 {
172 SlTableHeader(_view_desc);
173
174 SlSetArrayIndex(0);
175 SlGlobList(_view_desc);
176 }
177
178 void Load() const override
179 {
180 const std::vector<SaveLoad> slt = SlCompatTableHeader(_view_desc, _view_sl_compat);
181
183 SlGlobList(slt);
185 }
186};
187
188static const DATEChunkHandler DATE;
189static const VIEWChunkHandler VIEW;
190static const ChunkHandlerRef misc_chunk_handlers[] = {
191 DATE,
192 VIEW,
193};
194
195extern const ChunkHandlerTable _misc_chunk_handlers(misc_chunk_handlers);
A timeout timer will fire once after the interval.
Definition timer.h:116
static uint16_t sub_date_fract
Subpart of date_fract that we use when calendar days are slower than economy days.
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
static uint days_since_last_month
Number of days that have elapsed since the last month.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
uint _cur_company_tick_index
used to generate a name for one company that doesn't have a name yet per tick
TimeoutTimer< TimerGameTick > _new_competitor_timeout({ TimerGameTick::Priority::CompetitorTimeout, 0 }, []() { if(_game_mode==GameMode::Menu||!AI::CanStartNew()) return;if(_networking &&Company::GetNumItems() >=_settings_client.network.max_companies) return;if(_settings_game.difficulty.competitors_interval==0) return;uint8_t n=0;for(const Company *c :Company::Iterate()) { if(c->is_ai) n++;} if(n >=_settings_game.difficulty.max_no_competitors) return;Command< Commands::CompanyControl >::Post(CompanyCtrlAction::NewAI, CompanyID::Invalid(), CompanyRemoveReason::None, ClientID::Invalid);})
Start a new competitor company if possible.
uint16_t _disaster_delay
Delay counter for considering the next disaster.
Declarations for savegames operations.
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition fios_gui.cpp:41
GameSessionStats _game_session_stats
Statistics about the current session.
Definition gfx.cpp:52
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:51
Functions related to the gfx engine.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1553
bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
Zooms a viewport in a window in or out.
Definition main_gui.cpp:93
ZoomLevel _saved_scrollpos_zoom
Definition misc_sl.cpp:37
int _saved_scrollpos_x
Definition misc_sl.cpp:35
int _saved_scrollpos_y
Definition misc_sl.cpp:36
uint8_t _age_cargo_skip_counter
Skip aging of cargo? Used before savegame version 162.
Definition misc_sl.cpp:83
uint8_t _trees_tick_ctr
Determines when to consider building more trees.
Definition tree_cmd.cpp:45
Loading for misc chunks before table headers were added.
const SaveLoadCompat _date_check_sl_compat[]
Original field order for _date_check_desc.
const SaveLoadCompat _date_sl_compat[]
Original field order for _date_desc.
const SaveLoadCompat _view_sl_compat[]
Original field order for _view_desc.
Randomizer _random
Random used in the game state calculations.
Pseudo random number generator.
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:734
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition saveload.cpp:369
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
void SlGlobList(const SaveLoadTable &slt)
Save or Load (a list of) global variables.
Functions/types related to saving and loading games.
@ U64
A 64 bit unsigned int.
Definition saveload.h:686
@ U32
A 32 bit unsigned int.
Definition saveload.h:684
@ I32
A 32 bit signed int.
Definition saveload.h:683
@ U8
A 8 bit unsigned int.
Definition saveload.h:662
@ I16
A 16 bit signed int.
Definition saveload.h:663
@ U16
A 16 bit unsigned int.
Definition saveload.h:664
#define SLEG_CONDSSTR(name, variable, type, from, to)
Storage of a global std::string in some savegame versions.
Definition saveload.h:1155
#define SLEG_CONDVAR(name, variable, type, from, to)
Storage of a global variable in some savegame versions.
Definition saveload.h:1124
std::reference_wrapper< const ChunkHandler > ChunkHandlerRef
A reference to ChunkHandler.
Definition saveload.h:530
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition saveload.h:533
#define SLEG_VAR(name, variable, type)
Storage of a global variable in every savegame version.
Definition saveload.h:1201
std::span< const struct SaveLoadCompat > SaveLoadCompatTable
A table of SaveLoadCompat entries.
Definition saveload.h:539
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1278
@ BigDates
Saveload version: 31, SVN revision: 5999 Change date from 1920 - 2090 to 0 - 5 000 000.
Definition saveload.h:81
@ TownTolerancePauseMode
Saveload version: 4.0, SVN revision: 1 Town council tolerance and pause mode.
Definition saveload.h:38
@ U64TickCounter
Saveload version: 300, GitHub pull request: 10035 Make tick counter 64bit to avoid wrapping.
Definition saveload.h:340
@ AIStartDate
Saveload version: 309, GitHub pull request: 10653 Removal of individual AI start dates and added a g...
Definition saveload.h:350
@ MultipleRoadStops
Saveload version: 6.0, SVN revision: 1721 Multi tile road stops, and some map size related fixes.
Definition saveload.h:47
@ SavegameId
Saveload version: 313, GitHub pull request: 10719 Add an unique ID to every savegame (used to dedupl...
Definition saveload.h:355
@ NewGRFCustomCargoAging
Saveload version: 162, SVN revision: 22713 NewGRF influence on aging of cargo in vehicles.
Definition saveload.h:238
@ NextCompetitorStartOverflow
Saveload version: 109, SVN revision: 15075 Prevent overflow in the next competitor start counter.
Definition saveload.h:174
@ MinVersion
First savegame version.
Definition saveload.h:31
@ EconomyDate
Saveload version: 326, GitHub pull request: 10700 Split calendar and economy timers and dates.
Definition saveload.h:371
@ IndustryAcceptedHistory
Saveload version: 357, GitHub pull request: 14321 Add per-industry history of cargo delivered and wa...
Definition saveload.h:408
@ CalendarSubDateFract
Saveload version: 328, GitHub pull request: 11428 Add sub_date_fract to measure calendar days.
Definition saveload.h:373
@ MaxVersion
Highest possible saveload version.
Definition saveload.h:421
@ RiffToArray
Saveload version: 294, GitHub pull request: 9375 Changed many ChunkType::Riff chunks to ChunkType::A...
Definition saveload.h:332
std::span< const struct SaveLoad > SaveLoadTable
A table of SaveLoad entries.
Definition saveload.h:536
@ Table
An Array with a header describing the elements.
Definition saveload.h:475
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Definition of base types and functions in a cross-platform compatible way.
Save load date related variables as well as persistent tick counters.
Definition misc_sl.cpp:123
void Save() const override
Save the chunk.
Definition misc_sl.cpp:126
void Load() const override
Load the chunk.
Definition misc_sl.cpp:143
void LoadCheck(size_t) const override
Load the chunk for game preview.
Definition misc_sl.cpp:149
SaveLoad type struct.
Definition saveload.h:787
void Save() const override
Save the chunk.
Definition misc_sl.cpp:170
void Load() const override
Load the chunk.
Definition misc_sl.cpp:178
static constexpr VarType U16
Store a 16 bits unsigned int.
Definition saveload.h:754
static constexpr VarType U8
Store a 8 bits unsigned int.
Definition saveload.h:752
static constexpr VarType STR
Store string.
Definition saveload.h:760
static constexpr VarType U64
Store a 64 bits unsigned int.
Definition saveload.h:758
static constexpr VarType U32
Store a 32 bits unsigned int.
Definition saveload.h:756
static constexpr VarType I32
Store a 32 bits signed int.
Definition saveload.h:755
static constexpr VarType BOOL
Store a boolean (as int8).
Definition saveload.h:750
Data structure for viewport, display of a part of the world.
int width
Screen width of the viewport.
ZoomLevel zoom
The zoom level of the viewport.
int virtual_width
width << zoom
int height
Screen height of the viewport.
int virtual_height
height << zoom
Data structure for an opened window.
Definition window_gui.h:273
std::unique_ptr< ViewportData > viewport
Pointer to viewport data, if present.
Definition window_gui.h:318
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
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Functions related to (drawing on) viewports.
@ ZOOM_IN
Zoom in (get more detailed view).
@ ZOOM_NONE
Hack, used to update the button status.
@ ZOOM_OUT
Zoom out (get helicopter view).
Window * GetMainWindow()
Get the main window, i.e.
Definition window.cpp:1187
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1158
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:22
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:20
@ Max
Maximum zoom level.
Definition zoom_type.h:30
@ Min
Minimum zoom level.
Definition zoom_type.h:23
@ End
End for iteration.
Definition zoom_type.h:31