OpenTTD Source  12.0-beta2
saveload.cpp File Reference
#include "../stdafx.h"
#include "../debug.h"
#include "../station_base.h"
#include "../thread.h"
#include "../town.h"
#include "../network/network.h"
#include "../window_func.h"
#include "../strings_func.h"
#include "../core/endian_func.hpp"
#include "../vehicle_base.h"
#include "../company_func.h"
#include "../date_func.h"
#include "../autoreplace_base.h"
#include "../roadstop_base.h"
#include "../linkgraph/linkgraph.h"
#include "../linkgraph/linkgraphjob.h"
#include "../statusbar_gui.h"
#include "../fileio_func.h"
#include "../gamelog.h"
#include "../string_func.h"
#include "../fios.h"
#include "../error.h"
#include <atomic>
#include <deque>
#include <vector>
#include <string>
#include "table/strings.h"
#include "saveload_internal.h"
#include "saveload_filter.h"
#include "../safeguards.h"
#include <lzo/lzo1x.h>
#include <zlib.h>
#include <lzma.h>

Go to the source code of this file.

Data Structures

struct  ReadBuffer
 A buffer for reading (and buffering) savegame data. More...
 
struct  MemoryDumper
 Container for dumping the savegame (quickly) to memory. More...
 
struct  SaveLoadParams
 The saveload struct, containing reader-writer functions, buffer, version, etc. More...
 
class  SlStorageHelper< Tstorage, Tvar, Tallocator >
 Template class to help with list-like types. More...
 
class  SlSkipHandler
 Handler that is assigned when there is a struct read in the savegame which is not known to the code. More...
 
struct  FileReader
 Yes, simply reading from a file. More...
 
struct  FileWriter
 Yes, simply writing to a file. More...
 
struct  LZOLoadFilter
 Filter using LZO compression. More...
 
struct  LZOSaveFilter
 Filter using LZO compression. More...
 
struct  NoCompLoadFilter
 Filter without any compression. More...
 
struct  NoCompSaveFilter
 Filter without any compression. More...
 
struct  ZlibLoadFilter
 Filter using Zlib compression. More...
 
struct  ZlibSaveFilter
 Filter using Zlib compression. More...
 
struct  LZMALoadFilter
 Filter without any compression. More...
 
struct  LZMASaveFilter
 Filter using LZMA compression. More...
 
struct  SaveLoadFormat
 The format for a reader/writer type of a savegame. More...
 

Typedefs

typedef void(* AsyncSaveFinishProc) ()
 Callback for when the savegame loading is finished.
 

Enumerations

enum  SaveLoadAction {
  SLA_LOAD, SLA_SAVE, SLA_PTRS, SLA_NULL,
  SLA_LOAD_CHECK
}
 What are we currently doing? More...
 
enum  NeedLength { NL_NONE = 0, NL_WANTLENGTH = 1, NL_CALCLENGTH = 2 }
 

Functions

static const std::vector< ChunkHandlerRef > & ChunkHandlers ()
 
static void SlNullPointers ()
 Null all pointers (convert index -> nullptr)
 
void NORETURN SlError (StringID string, const char *extra_msg)
 Error handler. More...
 
void NORETURN SlErrorCorrupt (const char *msg)
 Error handler for corrupt savegames. More...
 
void NORETURN SlErrorCorruptFmt (const char *format,...)
 Issue an SlErrorCorrupt with a format string. More...
 
static void SetAsyncSaveFinish (AsyncSaveFinishProc proc)
 Called by save thread to tell we finished saving. More...
 
void ProcessAsyncSaveFinish ()
 Handle async save finishes.
 
byte SlReadByte ()
 Wrapper for reading a byte from the buffer. More...
 
void SlWriteByte (byte b)
 Wrapper for writing a byte to the dumper. More...
 
static int SlReadUint16 ()
 
static uint32 SlReadUint32 ()
 
static uint64 SlReadUint64 ()
 
static void SlWriteUint16 (uint16 v)
 
static void SlWriteUint32 (uint32 v)
 
static void SlWriteUint64 (uint64 x)
 
static uint SlReadSimpleGamma ()
 Read in the header descriptor of an object or an array. More...
 
static void SlWriteSimpleGamma (size_t i)
 Write the header descriptor of an object or an array. More...
 
static uint SlGetGammaLength (size_t i)
 Return how many bytes used to encode a gamma value.
 
static uint SlReadSparseIndex ()
 
static void SlWriteSparseIndex (uint index)
 
static uint SlReadArrayLength ()
 
static void SlWriteArrayLength (size_t length)
 
static uint SlGetArrayLength (size_t length)
 
static uint8 GetSavegameFileType (const SaveLoad &sld)
 Return the type as saved/loaded inside the savegame.
 
static uint SlCalcConvMemLen (VarType conv)
 Return the size in bytes of a certain type of normal/atomic variable as it appears in memory. More...
 
static byte SlCalcConvFileLen (VarType conv)
 Return the size in bytes of a certain type of normal/atomic variable as it appears in a saved game. More...
 
static size_t SlCalcRefLen ()
 Return the size in bytes of a reference (pointer)
 
void SlSetArrayIndex (uint index)
 
int SlIterateArray ()
 Iterate through the elements of an array and read the whole thing. More...
 
void SlSkipArray ()
 Skip an array or sparse array.
 
void SlSetLength (size_t length)
 Sets the length of either a RIFF object or the number of items in an array. More...
 
static void SlCopyBytes (void *ptr, size_t length)
 Save/Load bytes. More...
 
size_t SlGetFieldLength ()
 Get the length of the current object.
 
int64 ReadValue (const void *ptr, VarType conv)
 Return a signed-long version of the value of a setting. More...
 
void WriteValue (void *ptr, VarType conv, int64 val)
 Write the value of a setting. More...
 
static void SlSaveLoadConv (void *ptr, VarType conv)
 Handle all conversion and typechecking of variables here. More...
 
static size_t SlCalcNetStringLen (const char *ptr, size_t length)
 Calculate the net length of a string. More...
 
static size_t SlCalcStringLen (const void *ptr, size_t length, VarType conv)
 Calculate the gross length of the string that it will occupy in the savegame. More...
 
static size_t SlCalcStdStringLen (const void *ptr)
 Calculate the gross length of the string that it will occupy in the savegame. More...
 
static void SlString (void *ptr, size_t length, VarType conv)
 Save/Load a string. More...
 
static void SlStdString (void *ptr, VarType conv)
 Save/Load a std::string. More...
 
static void SlCopyInternal (void *object, size_t length, VarType conv)
 Internal function to save/Load a list of SL_VARs. More...
 
void SlCopy (void *object, size_t length, VarType conv)
 Copy a list of SL_VARs to/from a savegame. More...
 
static size_t SlCalcArrayLen (size_t length, VarType conv)
 Return the size in bytes of a certain type of atomic array. More...
 
static void SlArray (void *array, size_t length, VarType conv)
 Save/Load the length of the array followed by the array of SL_VAR elements. More...
 
static size_t ReferenceToInt (const void *obj, SLRefType rt)
 Pointers cannot be saved to a savegame, so this functions gets the index of the item, and if not available, it hussles with pointers (looks really bad :() Remember that a nullptr item has value 0, and all indices have +1, so vehicle 0 is saved as index 1. More...
 
static void * IntToReference (size_t index, SLRefType rt)
 Pointers cannot be loaded from a savegame, so this function gets the index from the savegame and returns the appropriate pointer from the already loaded base. More...
 
void SlSaveLoadRef (void *ptr, VarType conv)
 Handle conversion for references. More...
 
static size_t SlCalcRefListLen (const void *list, VarType conv)
 Return the size in bytes of a list. More...
 
static void SlRefList (void *list, VarType conv)
 Save/Load a list. More...
 
static size_t SlCalcDequeLen (const void *deque, VarType conv)
 Return the size in bytes of a std::deque. More...
 
static void SlDeque (void *deque, VarType conv)
 Save/load a std::deque. More...
 
static size_t SlCalcVectorLen (const void *vector, VarType conv)
 Return the size in bytes of a std::vector. More...
 
static void SlVector (void *vector, VarType conv)
 Save/load a std::vector. More...
 
static bool SlIsObjectValidInSavegame (const SaveLoad &sld)
 Are we going to save this object or not?
 
static size_t SlCalcTableHeader (const SaveLoadTable &slt)
 Calculate the size of the table header. More...
 
size_t SlCalcObjLength (const void *object, const SaveLoadTable &slt)
 Calculate the size of an object. More...
 
size_t SlCalcObjMemberLength (const void *object, const SaveLoad &sld)
 
static bool IsVariableSizeRight (const SaveLoad &sld)
 Check whether the variable size of the variable in the saveload configuration matches with the actual variable size. More...
 
static bool SlObjectMember (void *object, const SaveLoad &sld)
 
void SlSetStructListLength (size_t length)
 Set the length of this list. More...
 
size_t SlGetStructListLength (size_t limit)
 Get the length of this list; if it exceeds the limit, error out. More...
 
void SlObject (void *object, const SaveLoadTable &slt)
 Main SaveLoad function. More...
 
std::vector< SaveLoadSlTableHeader (const SaveLoadTable &slt)
 Save or Load a table header. More...
 
std::vector< SaveLoadSlCompatTableHeader (const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
 Load a table header in a savegame compatible way. More...
 
void SlGlobList (const SaveLoadTable &slt)
 Save or Load (a list of) global variables. More...
 
void SlAutolength (AutolengthProc *proc, void *arg)
 Do something of which I have no idea what it is :P. More...
 
static void SlLoadChunk (const ChunkHandler &ch)
 Load a chunk of data (eg vehicles, stations, etc.) More...
 
static void SlLoadCheckChunk (const ChunkHandler &ch)
 Load a chunk of data for checking savegames. More...
 
static void SlSaveChunk (const ChunkHandler &ch)
 Save a chunk of data (eg. More...
 
static void SlSaveChunks ()
 Save all chunks.
 
static const ChunkHandlerSlFindChunkHandler (uint32 id)
 Find the ChunkHandler that will be used for processing the found chunk in the savegame or in memory. More...
 
static void SlLoadChunks ()
 Load all chunks.
 
static void SlLoadCheckChunks ()
 Load all chunks for savegame checking.
 
static void SlFixPointers ()
 Fix all pointers (convert index -> pointer)
 
static const SaveLoadFormatGetSavegameFormat (const std::string &full_name, byte *compression_level)
 Return the savegameformat of the game. More...
 
void InitializeGame (uint size_x, uint size_y, bool reset_date, bool reset_settings)
 
bool AfterLoadGame ()
 Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill the caches for various purposes. More...
 
bool LoadOldSaveGame (const std::string &file)
 
static void ResetSaveloadData ()
 Clear temporary data that is passed between various saveload phases.
 
static void ClearSaveLoadState ()
 Clear/free saveload state.
 
static void SaveFileStart ()
 Update the gui accordingly when starting saving and set locks on saveload. More...
 
static void SaveFileDone ()
 Update the gui accordingly when saving is done and release locks on saveload.
 
void SetSaveLoadError (StringID str)
 Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friends)
 
const char * GetSaveLoadErrorString ()
 Get the string representation of the error message.
 
static void SaveFileError ()
 Show a gui message when saving has failed.
 
static SaveOrLoadResult SaveFileToDisk (bool threaded)
 We have written the whole game into memory, _memory_savegame, now find and appropriate compressor and start writing to file.
 
void WaitTillSaved ()
 
static SaveOrLoadResult DoSave (SaveFilter *writer, bool threaded)
 Actually perform the saving of the savegame. More...
 
SaveOrLoadResult SaveWithFilter (SaveFilter *writer, bool threaded)
 Save the game using a (writer) filter. More...
 
static SaveOrLoadResult DoLoad (LoadFilter *reader, bool load_check)
 Actually perform the loading of a "non-old" savegame. More...
 
SaveOrLoadResult LoadWithFilter (LoadFilter *reader)
 Load the game using a (reader) filter. More...
 
SaveOrLoadResult SaveOrLoad (const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
 Main Save or Load function where the high-level saveload functions are handled. More...
 
void DoAutoOrNetsave (FiosNumberedSaveName &counter)
 Create an autosave or netsave. More...
 
void DoExitSave ()
 Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
 
void GenerateDefaultSaveName (char *buf, const char *last)
 Fill the buffer with the default name for a savegame or screenshot. More...
 

Variables

const SaveLoadVersion SAVEGAME_VERSION = (SaveLoadVersion)(SL_MAX_VERSION - 1)
 Current savegame version of OpenTTD.
 
SavegameType _savegame_type
 type of savegame we are loading
 
FileToSaveLoad _file_to_saveload
 File to save or load in the openttd loop.
 
uint32 _ttdp_version
 version of TTDP savegame (if applicable)
 
SaveLoadVersion _sl_version
 the major savegame version identifier
 
byte _sl_minor_version
 the minor savegame version, DO NOT USE!
 
std::string _savegame_format
 how to compress savegames
 
bool _do_autosave
 are we doing an autosave at the moment?
 
static const size_t MEMORY_CHUNK_SIZE = 128 * 1024
 Save in chunks of 128 KiB.
 
static SaveLoadParams _sl
 Parameters used for/at saveload.
 
static std::atomic< AsyncSaveFinishProc_async_save_finish
 Callback to call when the savegame loading is finished.
 
static std::thread _save_thread
 The thread we're using to compress and write a savegame.
 
static size_t _next_offs
 
static const uint LZO_BUFFER_SIZE = 8192
 Buffer size for the LZO compressor.
 
static const lzma_stream _lzma_init = LZMA_STREAM_INIT
 Have a copy of an initialised LZMA stream. More...
 
static const SaveLoadFormat _saveload_formats []
 The different saveload formats known/understood by OpenTTD. More...
 

Detailed Description

All actions handling saving and loading goes on in this file. The general actions are as follows for saving a game (loading is analogous):

  1. initialize the writer by creating a temporary memory-buffer for it
  2. go through all to-be saved elements, each 'chunk' (ChunkHandler) prefixed by a label
  3. use their description array (SaveLoad) to know what elements to save and in what version of the game it was active (used when loading)
  4. write all data byte-by-byte to the temporary buffer so it is endian-safe
  5. when the buffer is full; flush it to the output (eg save to file) (_sl.buf, _sl.bufp, _sl.bufe)
  6. repeat this until everything is done, and flush any remaining output to file

Definition in file saveload.cpp.

Enumeration Type Documentation

◆ NeedLength

enum NeedLength
Enumerator
NL_NONE 

not working in NeedLength mode

NL_WANTLENGTH 

writing length and data

NL_CALCLENGTH 

need to calculate the length

Definition at line 80 of file saveload.cpp.

◆ SaveLoadAction

What are we currently doing?

Enumerator
SLA_LOAD 

loading

SLA_SAVE 

saving

SLA_PTRS 

fixing pointers

SLA_NULL 

null all pointers (on loading error)

SLA_LOAD_CHECK 

partial loading into _load_check_data

Definition at line 72 of file saveload.cpp.

Function Documentation

◆ AfterLoadGame()

bool AfterLoadGame ( )

Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill the caches for various purposes.

Returns
True iff conversion went without a problem.

Definition at line 545 of file afterload.cpp.

References MapSize(), and SetSignalHandlers().

◆ ChunkHandlers()

static const std::vector<ChunkHandlerRef>& ChunkHandlers ( )
static

List of all chunks in a savegame.

Definition at line 219 of file saveload.cpp.

Referenced by SlFindChunkHandler(), SlFixPointers(), SlNullPointers(), and SlSaveChunks().

◆ DoAutoOrNetsave()

void DoAutoOrNetsave ( FiosNumberedSaveName counter)

Create an autosave or netsave.

Parameters
counterA reference to the counter variable to be used for rotating the file name.
netsaveIndicates if this is a regular autosave or a netsave.

Definition at line 3331 of file saveload.cpp.

Referenced by ClientNetworkEmergencySave(), and DoAutosave().

◆ DoLoad()

static SaveOrLoadResult DoLoad ( LoadFilter reader,
bool  load_check 
)
static

Actually perform the loading of a "non-old" savegame.

Parameters
readerThe filter to read the savegame from.
load_checkWhether to perform the checking ("preview") or actually load the game.
Returns
Return the result of the action. SL_OK or SL_REINIT ("unload" the game)

Definition at line 3079 of file saveload.cpp.

References _load_check_data, _saveload_formats, _sl, _sl_minor_version, _sl_version, LoadCheckData::checkable, LoadCheckData::Clear(), Debug, endof, SaveLoadParams::lf, LoadFilter::Read(), LoadFilter::Reset(), SL_MIN_VERSION, and SlError().

Referenced by LoadWithFilter().

◆ DoSave()

static SaveOrLoadResult DoSave ( SaveFilter writer,
bool  threaded 
)
static

Actually perform the saving of the savegame.

General tactics is to first save the game to memory, then write it to file using the writer, either in threaded mode if possible, or single-threaded.

Parameters
writerThe filter to write the savegame to.
threadedWhether to try to perform the saving asynchronously.
Returns
Return the result of the action. SL_OK or SL_ERROR

Definition at line 3030 of file saveload.cpp.

References _sl, _sl_version, SaveLoadParams::dumper, SAVEGAME_VERSION, SaveLoadParams::saveinprogress, and SaveLoadParams::sf.

Referenced by SaveWithFilter().

◆ GenerateDefaultSaveName()

void GenerateDefaultSaveName ( char *  buf,
const char *  last 
)

◆ GetSavegameFormat()

static const SaveLoadFormat* GetSavegameFormat ( const std::string &  full_name,
byte *  compression_level 
)
static

Return the savegameformat of the game.

Whether it was created with ZLIB compression uncompressed, or another type

Parameters
full_nameName of the savegame format. If empty it picks the first available one
compression_levelOutput for telling what compression level we want.
Returns
Pointer to SaveLoadFormat struct giving all characteristics of this type of savegame

Definition at line 2840 of file saveload.cpp.

References _saveload_formats, Clamp(), SaveLoadFormat::default_compression, endof, SaveLoadFormat::init_write, lastof, SaveLoadFormat::name, SetDParamStr(), ShowErrorMessage(), and WL_CRITICAL.

Referenced by SaveFileToDisk().

◆ IntToReference()

static void* IntToReference ( size_t  index,
SLRefType  rt 
)
static

Pointers cannot be loaded from a savegame, so this function gets the index from the savegame and returns the appropriate pointer from the already loaded base.

Remember that an index of 0 is a nullptr pointer so all indices are +1 so vehicle 0 is saved as 1.

Parameters
indexThe index that is being converted to a pointer
rtSLRefType type of the object the pointer is sought of
Returns
Return the index converted to a pointer of any type

Definition at line 1260 of file saveload.cpp.

References _sl, SaveLoadParams::action, SpecializedStation< Station, false >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_vehicle_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_cargopacket_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_persistent_storage_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_link_graph_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_orderlist_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_link_graph_job_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_town_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_order_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_roadstop_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_enginerenew_pool >::Get(), IsSavegameVersionBefore(), SpecializedStation< Station, false >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_orderlist_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_link_graph_job_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_link_graph_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_persistent_storage_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_vehicle_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_town_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_roadstop_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_order_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_enginerenew_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_cargopacket_pool >::IsValidID(), REF_CARGO_PACKET, REF_ENGINE_RENEWS, REF_LINK_GRAPH, REF_LINK_GRAPH_JOB, REF_ORDER, REF_ORDERLIST, REF_ROADSTOPS, REF_STATION, REF_STORAGE, REF_TOWN, REF_VEHICLE, REF_VEHICLE_OLD, SLA_PTRS, SlErrorCorrupt(), SLV_4, and SLV_5.

◆ IsVariableSizeRight()

static bool IsVariableSizeRight ( const SaveLoad sld)
static

Check whether the variable size of the variable in the saveload configuration matches with the actual variable size.

Parameters
sldThe saveload configuration to test.

Definition at line 1657 of file saveload.cpp.

References SaveLoad::cmd, SaveLoad::conv, GetVarMemType(), SL_VAR, and SLE_VAR_NULL.

◆ LoadWithFilter()

SaveOrLoadResult LoadWithFilter ( LoadFilter reader)

Load the game using a (reader) filter.

Parameters
readerThe filter to read the savegame from.
Returns
Return the result of the action. SL_OK or SL_REINIT ("unload" the game)

Definition at line 3220 of file saveload.cpp.

References _sl, SaveLoadParams::action, ClearSaveLoadState(), DoLoad(), SL_REINIT, and SLA_LOAD.

◆ ReadValue()

int64 ReadValue ( const void *  ptr,
VarType  conv 
)

Return a signed-long version of the value of a setting.

Parameters
ptrpointer to the variable
convtype of variable, can be a non-clean type, eg one with other flags because it is parsed
Returns
returns the value of the pointer-setting

Definition at line 804 of file saveload.cpp.

References GetVarMemType().

Referenced by IntSettingDesc::Read().

◆ ReferenceToInt()

static size_t ReferenceToInt ( const void *  obj,
SLRefType  rt 
)
static

Pointers cannot be saved to a savegame, so this functions gets the index of the item, and if not available, it hussles with pointers (looks really bad :() Remember that a nullptr item has value 0, and all indices have +1, so vehicle 0 is saved as index 1.

Parameters
objThe object that we want to get the index of
rtSLRefType type of the object the index is being sought of
Returns
Return the pointer converted to an index of the type pointed to

Definition at line 1227 of file saveload.cpp.

References _sl, SaveLoadParams::action, REF_CARGO_PACKET, REF_ENGINE_RENEWS, REF_LINK_GRAPH, REF_LINK_GRAPH_JOB, REF_ORDER, REF_ORDERLIST, REF_ROADSTOPS, REF_STATION, REF_STORAGE, REF_TOWN, REF_VEHICLE, REF_VEHICLE_OLD, and SLA_SAVE.

◆ SaveFileStart()

static void SaveFileStart ( )
static

Update the gui accordingly when starting saving and set locks on saveload.

Also turn off fast-forward cause with that saving takes Aaaaages

Definition at line 2919 of file saveload.cpp.

References _game_speed, _sl, SaveLoadParams::game_speed, InvalidateWindowData(), SaveLoadParams::saveinprogress, SBI_SAVELOAD_START, SetMouseCursorBusy(), and WC_STATUS_BAR.

◆ SaveOrLoad()

SaveOrLoadResult SaveOrLoad ( const std::string &  filename,
SaveLoadOperation  fop,
DetailedFileType  dft,
Subdirectory  sb,
bool  threaded 
)

Main Save or Load function where the high-level saveload functions are handled.

It opens the savegame, selects format and checks versions

Parameters
filenameThe name of the savegame being created/loaded
fopSave or load mode. Load can also be a TTD(Patch) game.
sbThe sub directory to save the savegame in
threadedTrue when threaded saving is allowed
Returns
Return the result of the action. SL_OK, SL_ERROR, or SL_REINIT ("unload" the game)

Definition at line 3240 of file saveload.cpp.

References _do_autosave, _sl, DFT_GAME_FILE, INVALID_STRING_ID, SaveLoadParams::saveinprogress, ShowErrorMessage(), SL_OK, SLO_SAVE, and WL_ERROR.

Referenced by DEF_CONSOLE_CMD(), DoExitSave(), VideoDriver_Dedicated::MainLoop(), and CrashLog::WriteSavegame().

◆ SaveWithFilter()

SaveOrLoadResult SaveWithFilter ( SaveFilter writer,
bool  threaded 
)

Save the game using a (writer) filter.

Parameters
writerThe filter to write the savegame to.
threadedWhether to try to perform the saving asynchronously.
Returns
Return the result of the action. SL_OK or SL_ERROR

Definition at line 3062 of file saveload.cpp.

References _sl, SaveLoadParams::action, ClearSaveLoadState(), DoSave(), SL_ERROR, and SLA_SAVE.

◆ SetAsyncSaveFinish()

static void SetAsyncSaveFinish ( AsyncSaveFinishProc  proc)
static

Called by save thread to tell we finished saving.

Parameters
procThe callback to call when saving is done.

Definition at line 397 of file saveload.cpp.

◆ SlArray()

static void SlArray ( void *  array,
size_t  length,
VarType  conv 
)
static

Save/Load the length of the array followed by the array of SL_VAR elements.

Parameters
arrayThe array being manipulated
lengthThe length of the array in elements
convVarType type of the atomic array (int, byte, uint64, etc.)

Definition at line 1181 of file saveload.cpp.

References _sl, SaveLoadParams::action, and SLA_SAVE.

◆ SlAutolength()

void SlAutolength ( AutolengthProc *  proc,
void *  arg 
)

Do something of which I have no idea what it is :P.

Parameters
procThe callback procedure that is called
argThe variable that will be used for the callback procedure

Definition at line 2093 of file saveload.cpp.

◆ SlCalcArrayLen()

static size_t SlCalcArrayLen ( size_t  length,
VarType  conv 
)
inlinestatic

Return the size in bytes of a certain type of atomic array.

Parameters
lengthThe length of the array counted in elements
convVarType type of the variable that is used in calculating the size

Definition at line 1170 of file saveload.cpp.

References SlCalcConvFileLen().

◆ SlCalcConvFileLen()

static byte SlCalcConvFileLen ( VarType  conv)
inlinestatic

Return the size in bytes of a certain type of normal/atomic variable as it appears in a saved game.

See VarTypes

Parameters
convVarType type of variable that is used for calculating the size
Returns
Return the size of this type in bytes

Definition at line 643 of file saveload.cpp.

References GetVarFileType(), and lengthof.

Referenced by SlCalcArrayLen(), SlCalcTableHeader(), SlCopy(), and SlCopyInternal().

◆ SlCalcConvMemLen()

static uint SlCalcConvMemLen ( VarType  conv)
inlinestatic

Return the size in bytes of a certain type of normal/atomic variable as it appears in memory.

See VarTypes

Parameters
convVarType type of variable that is used for calculating the size
Returns
Return the size of this type in bytes

Definition at line 620 of file saveload.cpp.

References GetVarMemType(), SLE_VAR_STR, SLE_VAR_STRB, and SLE_VAR_STRQ.

◆ SlCalcDequeLen()

static size_t SlCalcDequeLen ( const void *  deque,
VarType  conv 
)
inlinestatic

Return the size in bytes of a std::deque.

Parameters
dequeThe std::deque to find the size of
convVarType type of variable that is used for calculating the size

Definition at line 1475 of file saveload.cpp.

References GetVarMemType().

◆ SlCalcNetStringLen()

static size_t SlCalcNetStringLen ( const char *  ptr,
size_t  length 
)
inlinestatic

Calculate the net length of a string.

This is in almost all cases just strlen(), but if the string is not properly terminated, we'll resort to the maximum length of the buffer.

Parameters
ptrpointer to the stringbuffer
lengthmaximum length of the string (buffer). If -1 we don't care about a maximum length, but take string length as it is.
Returns
return the net length of the string

Definition at line 911 of file saveload.cpp.

◆ SlCalcObjLength()

size_t SlCalcObjLength ( const void *  object,
const SaveLoadTable slt 
)

Calculate the size of an object.

Parameters
objectto be measured.
sltThe SaveLoad table with objects to save/load.
Returns
size of given object.

Definition at line 1594 of file saveload.cpp.

Referenced by SlObject().

◆ SlCalcRefListLen()

static size_t SlCalcRefListLen ( const void *  list,
VarType  conv 
)
inlinestatic

Return the size in bytes of a list.

Parameters
listThe std::list to find the size of.
convVarType type of variable that is used for calculating the size.

Definition at line 1448 of file saveload.cpp.

References SL_REF, and SlStorageHelper< Tstorage, Tvar, Tallocator >::SlCalcLen().

Referenced by SlRefList().

◆ SlCalcStdStringLen()

static size_t SlCalcStdStringLen ( const void *  ptr)
inlinestatic

Calculate the gross length of the string that it will occupy in the savegame.

This includes the real length, returned by SlCalcNetStringLen and the length that the index will occupy.

Parameters
ptrPointer to the std::string.
Returns
The gross length of the string.

Definition at line 955 of file saveload.cpp.

◆ SlCalcStringLen()

static size_t SlCalcStringLen ( const void *  ptr,
size_t  length,
VarType  conv 
)
inlinestatic

Calculate the gross length of the string that it will occupy in the savegame.

This includes the real length, returned by SlCalcNetStringLen and the length that the index will occupy.

Parameters
ptrpointer to the stringbuffer
lengthmaximum length of the string (buffer size, etc.)
convtype of data been used
Returns
return the gross length of the string

Definition at line 926 of file saveload.cpp.

References GetVarMemType().

◆ SlCalcTableHeader()

static size_t SlCalcTableHeader ( const SaveLoadTable slt)
static

Calculate the size of the table header.

Parameters
sltThe SaveLoad table with objects to save/load.
Returns
size of given object.

Definition at line 1565 of file saveload.cpp.

References SlCalcConvFileLen(), and SlIsObjectValidInSavegame().

◆ SlCalcVectorLen()

static size_t SlCalcVectorLen ( const void *  vector,
VarType  conv 
)
inlinestatic

Return the size in bytes of a std::vector.

Parameters
vectorThe std::vector to find the size of
convVarType type of variable that is used for calculating the size

Definition at line 1517 of file saveload.cpp.

References GetVarMemType().

◆ SlCompatTableHeader()

std::vector<SaveLoad> SlCompatTableHeader ( const SaveLoadTable slt,
const SaveLoadCompatTable slct 
)

Load a table header in a savegame compatible way.

If the savegame was made before table headers were added, it will fall back to the SaveLoadCompatTable for the order of fields while loading.

Note
You only have to call this function if the chunk existed as a non-table type before converting it to a table. New chunks created as table can call SlTableHeader() directly.
Parameters
sltThe SaveLoad table with objects to save/load.
slctThe SaveLoadCompat table the original order of the fields.
Returns
When loading, the ordered SaveLoad array to use; otherwise an empty list.

Definition at line 2029 of file saveload.cpp.

References _sl, SaveLoadParams::action, SaveLoadParams::block_mode, SLA_LOAD, and SLA_LOAD_CHECK.

Referenced by NewGRFMappingChunkHandler::Load(), PSACChunkHandler::Load(), GOALChunkHandler::Load(), ERNWChunkHandler::Load(), MAPSChunkHandler::Load(), GRPSChunkHandler::Load(), DEPTChunkHandler::Load(), SUBSChunkHandler::Load(), SIGNChunkHandler::Load(), OBJSChunkHandler::Load(), CHTSChunkHandler::Load(), STPEChunkHandler::Load(), GSDTChunkHandler::Load(), AIPLChunkHandler::Load(), CMDLChunkHandler::Load(), ECMYChunkHandler::Load(), INDYChunkHandler::Load(), STPAChunkHandler::Load(), ENGNChunkHandler::Load(), CAPYChunkHandler::Load(), CMPUChunkHandler::Load(), CAPAChunkHandler::Load(), RAILChunkHandler::Load(), IBLDChunkHandler::Load(), VIEWChunkHandler::Load(), GSTRChunkHandler::Load(), ITBLChunkHandler::Load(), EIDSChunkHandler::Load(), ORDLChunkHandler::Load(), LGRPChunkHandler::Load(), LGRJChunkHandler::Load(), CITYChunkHandler::Load(), BKORChunkHandler::Load(), LGRSChunkHandler::Load(), STNSChunkHandler::Load(), PLYRChunkHandler::Load(), STNNChunkHandler::Load(), ROADChunkHandler::Load(), VEHSChunkHandler::Load(), MAPSChunkHandler::LoadCheck(), PLYRChunkHandler::LoadCheck(), and LoadSettings().

◆ SlCopy()

void SlCopy ( void *  object,
size_t  length,
VarType  conv 
)

Copy a list of SL_VARs to/from a savegame.

These entries are copied as-is, and you as caller have to make sure things like length-fields are calculated correctly.

Parameters
objectThe object being manipulated.
lengthThe length of the object in elements
convVarType type of the items.

Definition at line 1151 of file saveload.cpp.

References _sl, SaveLoadParams::action, SaveLoadParams::need_length, NL_CALCLENGTH, NL_NONE, SLA_NULL, SLA_PTRS, SlCalcConvFileLen(), SlCopyInternal(), and SlSetLength().

Referenced by ANITChunkHandler::Load(), MAPTChunkHandler::Load(), MAPHChunkHandler::Load(), NAMEChunkHandler::Load(), MAPOChunkHandler::Load(), MAP2ChunkHandler::Load(), ENGSChunkHandler::Load(), M3LOChunkHandler::Load(), M3HIChunkHandler::Load(), MAP5ChunkHandler::Load(), MAPEChunkHandler::Load(), MAP7ChunkHandler::Load(), MAP8ChunkHandler::Load(), and ScriptInstance::LoadObjects().

◆ SlCopyBytes()

static void SlCopyBytes ( void *  ptr,
size_t  length 
)
static

Save/Load bytes.

These do not need to be converted to Little/Big Endian so directly write them or read them to/from file

Parameters
ptrThe source or destination of the object being manipulated
lengthnumber of bytes this fast CopyBytes lasts

Definition at line 775 of file saveload.cpp.

References _sl, SaveLoadParams::action, SLA_LOAD, SLA_LOAD_CHECK, SLA_SAVE, SlReadByte(), and SlWriteByte().

◆ SlCopyInternal()

static void SlCopyInternal ( void *  object,
size_t  length,
VarType  conv 
)
static

Internal function to save/Load a list of SL_VARs.

SlCopy() and SlArray() are very similar, with the exception of the header. This function represents the common part.

Parameters
objectThe object being manipulated.
lengthThe length of the object in elements
convVarType type of the items.

Definition at line 1102 of file saveload.cpp.

References _sl, _sl_version, SaveLoadParams::action, GetVarMemType(), SLA_SAVE, SlCalcConvFileLen(), SLE_VAR_NULL, and SlSkipBytes().

Referenced by SlCopy().

◆ SlDeque()

static void SlDeque ( void *  deque,
VarType  conv 
)
static

Save/load a std::deque.

Parameters
dequeThe std::deque being manipulated
convVarType type of variable that is used for calculating the size

Definition at line 1496 of file saveload.cpp.

References GetVarMemType().

◆ SlError()

void NORETURN SlError ( StringID  string,
const char *  extra_msg 
)

Error handler.

Sets everything up to show an error message and to clean up the mess of a partial savegame load.

Parameters
stringThe translatable error message to show.
extra_msgAn extra error message coming from one of the APIs.
Note
This function does never return as it throws an exception to break out of all the saveload code.

Definition at line 332 of file saveload.cpp.

References _load_check_data, _sl, SaveLoadParams::action, LoadCheckData::error, LoadCheckData::error_data, SaveLoadParams::error_str, SaveLoadParams::extra_msg, free(), SLA_LOAD, SLA_LOAD_CHECK, SLA_PTRS, SlNullPointers(), and stredup().

Referenced by DoLoad(), PacketWriter::Finish(), LZMALoadFilter::LZMALoadFilter(), LZMASaveFilter::LZMASaveFilter(), LZOLoadFilter::LZOLoadFilter(), LZOSaveFilter::LZOSaveFilter(), LZMALoadFilter::Read(), SlErrorCorrupt(), PacketWriter::Write(), FileWriter::Write(), ZlibSaveFilter::WriteLoop(), LZMASaveFilter::WriteLoop(), and ZlibSaveFilter::ZlibSaveFilter().

◆ SlErrorCorrupt()

void NORETURN SlErrorCorrupt ( const char *  msg)

Error handler for corrupt savegames.

Sets everything up to show the error message and to clean up the mess of a partial savegame load.

Parameters
msgLocation the corruption has been spotted.
Note
This function does never return as it throws an exception to break out of all the saveload code.

Definition at line 364 of file saveload.cpp.

References SlError().

Referenced by IntToReference(), NewGRFMappingChunkHandler::Load(), CHTSChunkHandler::Load(), NAMEChunkHandler::Load(), IBLDChunkHandler::Load(), ITBLChunkHandler::Load(), LGRSChunkHandler::Load(), LoadSettings(), SetWaterClassDependingOnSurroundings(), SlErrorCorruptFmt(), and SlReadSimpleGamma().

◆ SlErrorCorruptFmt()

void NORETURN SlErrorCorruptFmt ( const char *  format,
  ... 
)

Issue an SlErrorCorrupt with a format string.

Parameters
formatformat string
...arguments to format string
Note
This function does never return as it throws an exception to break out of all the saveload code.

Definition at line 376 of file saveload.cpp.

References lastof, SlErrorCorrupt(), and vseprintf().

◆ SlFindChunkHandler()

static const ChunkHandler* SlFindChunkHandler ( uint32  id)
static

Find the ChunkHandler that will be used for processing the found chunk in the savegame or in memory.

Parameters
idthe chunk in question
Returns
returns the appropriate chunkhandler

Definition at line 2289 of file saveload.cpp.

References ChunkHandlers().

◆ SlGetStructListLength()

size_t SlGetStructListLength ( size_t  limit)

Get the length of this list; if it exceeds the limit, error out.

Parameters
limitThe maximum size the list can be.
Returns
The length of the list.

Definition at line 1825 of file saveload.cpp.

Referenced by SlTownSupplied::GetNumCargo(), SlStationGoods::GetNumCargo(), and SlSkipHandler::Load().

◆ SlGlobList()

void SlGlobList ( const SaveLoadTable slt)

Save or Load (a list of) global variables.

Parameters
sltThe SaveLoad table with objects to save/load.

Definition at line 2083 of file saveload.cpp.

References SlObject().

Referenced by IBLDChunkHandler::Load().

◆ SlIterateArray()

int SlIterateArray ( )

◆ SlLoadCheckChunk()

static void SlLoadCheckChunk ( const ChunkHandler ch)
static

Load a chunk of data for checking savegames.

If the chunkhandler is nullptr, the chunk is skipped.

Parameters
chThe chunkhandler that will be used for the operation

Definition at line 2189 of file saveload.cpp.

References _sl, SaveLoadParams::block_mode, CH_TYPE_MASK, SaveLoadParams::expect_table_header, SaveLoadParams::obj_len, and SlReadByte().

◆ SlLoadChunk()

static void SlLoadChunk ( const ChunkHandler ch)
static

Load a chunk of data (eg vehicles, stations, etc.)

Parameters
chThe chunkhandler that will be used for the operation

Definition at line 2139 of file saveload.cpp.

References _sl, SaveLoadParams::block_mode, CH_TYPE_MASK, SaveLoadParams::expect_table_header, SaveLoadParams::obj_len, and SlReadByte().

◆ SlObject()

◆ SlReadByte()

byte SlReadByte ( )

Wrapper for reading a byte from the buffer.

Returns
The read byte.

Definition at line 424 of file saveload.cpp.

References _sl, and SaveLoadParams::reader.

Referenced by SlCopyBytes(), SlLoadCheckChunk(), SlLoadChunk(), SlReadSimpleGamma(), and SlSkipBytes().

◆ SlReadSimpleGamma()

static uint SlReadSimpleGamma ( )
static

Read in the header descriptor of an object or an array.

If the highest bit is set (7), then the index is bigger than 127 elements, so use the next byte to read in the real value. The actual value is then both bytes added with the first shifted 8 bits to the left, and dropping the highest bit (which only indicated a big index). x = ((x & 0x7F) << 8) + SlReadByte();

Returns
Return the value of the index

Definition at line 484 of file saveload.cpp.

References HasBit(), SlErrorCorrupt(), and SlReadByte().

◆ SlRefList()

static void SlRefList ( void *  list,
VarType  conv 
)
static

Save/Load a list.

Parameters
listThe list being manipulated.
convVarType type of variable that is used for calculating the size.

Definition at line 1458 of file saveload.cpp.

References _sl, SaveLoadParams::need_length, NL_CALCLENGTH, NL_NONE, SL_REF, SlCalcRefListLen(), SlStorageHelper< Tstorage, Tvar, Tallocator >::SlSaveLoad(), and SlSetLength().

◆ SlSaveChunk()

static void SlSaveChunk ( const ChunkHandler ch)
static

Save a chunk of data (eg.

vehicles, stations, etc.). Each chunk is prefixed by an ID identifying it, followed by data, and terminator where appropriate

Parameters
chThe chunkhandler that will be used for the operation

Definition at line 2237 of file saveload.cpp.

References CH_READONLY, and ChunkHandler::type.

Referenced by SlSaveChunks().

◆ SlSaveLoadConv()

static void SlSaveLoadConv ( void *  ptr,
VarType  conv 
)
static

Handle all conversion and typechecking of variables here.

In the case of saving, read in the actual value from the struct and then write them to file, endian safely. Loading a value goes exactly the opposite way

Parameters
ptrThe object being filled/read
convVarType type of the current element of the struct

Definition at line 854 of file saveload.cpp.

References _sl, SaveLoadParams::action, and SLA_SAVE.

◆ SlSaveLoadRef()

void SlSaveLoadRef ( void *  ptr,
VarType  conv 
)

Handle conversion for references.

Parameters
ptrThe object being filled/read.
convVarType type of the current element of the struct.

Definition at line 1336 of file saveload.cpp.

References _sl, SaveLoadParams::action, and SLA_SAVE.

◆ SlSetLength()

void SlSetLength ( size_t  length)

Sets the length of either a RIFF object or the number of items in an array.

This lets us load an object or an array of arbitrary size

Parameters
lengthThe length of the sought object/array

Definition at line 723 of file saveload.cpp.

References _sl, SaveLoadParams::action, SaveLoadParams::block_mode, SaveLoadParams::need_length, NL_NONE, NL_WANTLENGTH, and SLA_SAVE.

Referenced by MAPTChunkHandler::Save(), MAPHChunkHandler::Save(), MAPOChunkHandler::Save(), MAP2ChunkHandler::Save(), M3LOChunkHandler::Save(), M3HIChunkHandler::Save(), MAP5ChunkHandler::Save(), MAPEChunkHandler::Save(), MAP7ChunkHandler::Save(), MAP8ChunkHandler::Save(), SlCopy(), SlObject(), SlRefList(), and SlSetStructListLength().

◆ SlSetStructListLength()

void SlSetStructListLength ( size_t  length)

Set the length of this list.

Parameters
Thelength of the list.

Definition at line 1809 of file saveload.cpp.

References _sl, SaveLoadParams::need_length, NL_NONE, and SlSetLength().

◆ SlStdString()

static void SlStdString ( void *  ptr,
VarType  conv 
)
static

Save/Load a std::string.

Parameters
ptrthe string being manipulated
convmust be SLE_FILE_STRING

Definition at line 1048 of file saveload.cpp.

References _sl, SaveLoadParams::action, and SLA_SAVE.

◆ SlString()

static void SlString ( void *  ptr,
size_t  length,
VarType  conv 
)
static

Save/Load a string.

Parameters
ptrthe string being manipulated
lengthof the string (full length)
convmust be SLE_FILE_STRING

Definition at line 969 of file saveload.cpp.

References _sl, SaveLoadParams::action, GetVarMemType(), and SLA_SAVE.

◆ SlTableHeader()

◆ SlVector()

static void SlVector ( void *  vector,
VarType  conv 
)
static

Save/load a std::vector.

Parameters
vectorThe std::vector being manipulated
convVarType type of variable that is used for calculating the size

Definition at line 1538 of file saveload.cpp.

References GetVarMemType().

◆ SlWriteByte()

void SlWriteByte ( byte  b)

Wrapper for writing a byte to the dumper.

Parameters
bThe byte to write.

Definition at line 433 of file saveload.cpp.

References _sl, SaveLoadParams::dumper, and MemoryDumper::WriteByte().

Referenced by SlCopyBytes().

◆ SlWriteSimpleGamma()

static void SlWriteSimpleGamma ( size_t  i)
static

Write the header descriptor of an object or an array.

If the element is bigger than 127, use 2 bytes for saving and use the highest byte of the first written one as a notice that the length consists of 2 bytes, etc.. like this: 0xxxxxxx 10xxxxxx xxxxxxxx 110xxxxx xxxxxxxx xxxxxxxx 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx 11110— xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx We could extend the scheme ad infinum to support arbitrarily large chunks, but as sizeof(size_t) == 4 is still very common we don't support anything above 32 bits. That's why in the last case the 3 most significant bits are unused.

Parameters
iIndex being written

Definition at line 526 of file saveload.cpp.

◆ WriteValue()

void WriteValue ( void *  ptr,
VarType  conv,
int64  val 
)

Write the value of a setting.

Parameters
ptrpointer to the variable
convtype of variable, can be a non-clean type, eg with other flags. It is parsed upon read
valthe new value being given to the variable

Definition at line 828 of file saveload.cpp.

References GetVarMemType().

Referenced by IntSettingDesc::Write().

Variable Documentation

◆ _lzma_init

const lzma_stream _lzma_init = LZMA_STREAM_INIT
static

Have a copy of an initialised LZMA stream.

We need this as it's impossible to "re"-assign LZMA_STREAM_INIT to a variable in some compilers, i.e. LZMA_STREAM_INIT can't be used to set something. This var has to be used instead.

Definition at line 2680 of file saveload.cpp.

◆ _saveload_formats

const SaveLoadFormat _saveload_formats[]
static
Initial value:
= {
{"lzo", TO_BE32X('OTTD'), CreateLoadFilter<LZOLoadFilter>, CreateSaveFilter<LZOSaveFilter>, 0, 0, 0},
{"none", TO_BE32X('OTTN'), CreateLoadFilter<NoCompLoadFilter>, CreateSaveFilter<NoCompSaveFilter>, 0, 0, 0},
{"zlib", TO_BE32X('OTTZ'), CreateLoadFilter<ZlibLoadFilter>, CreateSaveFilter<ZlibSaveFilter>, 0, 6, 9},
{"lzma", TO_BE32X('OTTX'), CreateLoadFilter<LZMALoadFilter>, CreateSaveFilter<LZMASaveFilter>, 0, 2, 9},
}

The different saveload formats known/understood by OpenTTD.

Definition at line 2804 of file saveload.cpp.

Referenced by DoLoad(), and GetSavegameFormat().