4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
12 * All actions handling saving and loading goes on in this file. The general actions
13 * are as follows for saving a game (loading is analogous):
15 * <li>initialize the writer by creating a temporary memory-buffer for it
16 * <li>go through all to-be saved elements, each 'chunk' (#ChunkHandler) prefixed by a label
17 * <li>use their description array (#SaveLoad) to know what elements to save and in what version
18 * of the game it was active (used when loading)
19 * <li>write all data byte-by-byte to the temporary buffer so it is endian-safe
20 * <li>when the buffer is full; flush it to the output (eg save to file) (_sl.buf, _sl.bufp, _sl.bufe)
21 * <li>repeat this until everything is done, and flush any remaining output to file
24 #include "../stdafx.h"
26 #include "../station_base.h"
27 #include "../dock_base.h"
28 #include "../thread/thread.h"
30 #include "../network/network.h"
31 #include "../window_func.h"
32 #include "../strings_func.h"
33 #include "../core/endian_func.hpp"
34 #include "../vehicle_base.h"
35 #include "../company_func.h"
36 #include "../date_func.h"
37 #include "../autoreplace_base.h"
38 #include "../roadstop_base.h"
39 #include "../linkgraph/linkgraph.h"
40 #include "../linkgraph/linkgraphjob.h"
41 #include "../statusbar_gui.h"
42 #include "../fileio_func.h"
43 #include "../gamelog.h"
44 #include "../string_func.h"
45 #include "../string_func_extra.h"
49 #include "../tbtr_template_vehicle.h"
51 #include "table/strings.h"
53 #include "saveload_internal.h"
54 #include "saveload_filter.h"
56 #include "../safeguards.h"
62 * Previous savegame versions, the trunk revision where they were
63 * introduced and the released version that had that particular
65 * Up to savegame version 18 there is a minor version as well.
72 * 4.1 122 0.3.3, 0.3.4
88 * 13.1 2080 0.4.0, 0.4.0.1
250 * 173 23967 1.2.0-RC1
271 * 194 26881 1.5.x, 1.6.0
278 * 256 SL_PATCH_PACK_DAYLENGTH
279 * 257 SL_PATCH_PACK_TOWN_BUILDINGS
280 * 258 SL_PATCH_PACK_MAP_FEATURES
281 * 259 SL_PATCH_PACK_SAFE_WAITING_LOCATION
282 * 260 SL_PATCH_PACK_1_2
283 * 261 SL_PATCH_PACK_1_3
284 * 262 SL_PATCH_PACK_1_4
285 * 263 SL_PATCH_PACK_1_5
286 * 264 SL_PATCH_PACK_1_6
287 * 265 SL_PATCH_PACK_1_7
288 * 266 SL_PATCH_PACK_1_8
289 * 267 SL_PATCH_PACK_1_9
290 * 268 SL_PATCH_PACK_1_10
291 * 269 SL_PATCH_PACK_1_11
292 * 270 SL_PATCH_PACK_1_12
293 * 271 SL_PATCH_PACK_1_14
294 * 272 SL_PATCH_PACK_1_15
295 * 273 SL_PATCH_PACK_1_16
296 * 274 SL_PATCH_PACK_1_18
297 * 275 SL_PATCH_PACK_1_18_3
298 * 276 SL_PATCH_PACK_1_18_4
299 * 277 SL_PATCH_PACK_1_18_6
300 * 278 SL_PATCH_PACK_1_19
301 * 279 SL_PATCH_PACK_1_20
302 * 280 SL_PATCH_PACK_1_21
303 * 281 SL_PATCH_PACK_1_22
304 * 282 SL_PATCH_PACK_1_23
305 * 283 SL_PATCH_PACK_1_24
306 * 284 SL_PATCH_PACK_1_25
307 * 285 SL_PATCH_PACK_1_26
308 * 286 SL_PATCH_PACK_1_27
310 extern const uint16 SAVEGAME_VERSION
= SL_PATCH_PACK_1_27
; ///< Current savegame version of OpenTTD.
312 SavegameType _savegame_type
; ///< type of savegame we are loading
313 FileToSaveLoad _file_to_saveload
; ///< File to save or load in the openttd loop.
315 uint32 _ttdp_version
; ///< version of TTDP savegame (if applicable)
316 uint16 _sl_version
; ///< the major savegame version identifier
317 byte _sl_minor_version
; ///< the minor savegame version, DO NOT USE!
318 char _savegame_format
[8]; ///< how to compress savegames
319 bool _do_autosave
; ///< are we doing an autosave at the moment?
321 /** What are we currently doing? */
322 enum SaveLoadAction
{
323 SLA_LOAD
, ///< loading
324 SLA_SAVE
, ///< saving
325 SLA_PTRS
, ///< fixing pointers
326 SLA_NULL
, ///< null all pointers (on loading error)
327 SLA_LOAD_CHECK
, ///< partial loading into #_load_check_data
331 NL_NONE
= 0, ///< not working in NeedLength mode
332 NL_WANTLENGTH
= 1, ///< writing length and data
333 NL_CALCLENGTH
= 2, ///< need to calculate the length
336 /** Save in chunks of 128 KiB. */
337 static const size_t MEMORY_CHUNK_SIZE
= 128 * 1024;
339 /** A buffer for reading (and buffering) savegame data. */
341 byte buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer we're going to read from.
342 byte
*bufp
; ///< Location we're at reading the buffer.
343 byte
*bufe
; ///< End of the buffer we can read from.
344 LoadFilter
*reader
; ///< The filter used to actually read.
345 size_t read
; ///< The amount of read bytes so far from the filter.
348 * Initialise our variables.
349 * @param reader The filter to actually read data.
351 ReadBuffer(LoadFilter
*reader
) : bufp(nullptr), bufe(nullptr), reader(reader
), read(0)
355 inline byte
ReadByte()
357 if (this->bufp
== this->bufe
) {
358 size_t len
= this->reader
->Read(this->buf
, lengthof(this->buf
));
359 if (len
== 0) SlErrorCorrupt("Unexpected end of chunk");
362 this->bufp
= this->buf
;
363 this->bufe
= this->buf
+ len
;
366 return *this->bufp
++;
370 * Get the size of the memory dump made so far.
373 size_t GetSize() const
375 return this->read
- (this->bufe
- this->bufp
);
380 /** Container for dumping the savegame (quickly) to memory. */
381 struct MemoryDumper
{
382 AutoFreeSmallVector
<byte
*, 16> blocks
; ///< Buffer with blocks of allocated memory.
383 byte
*buf
; ///< Buffer we're going to write to.
384 byte
*bufe
; ///< End of the buffer we write to.
386 /** Initialise our variables. */
387 MemoryDumper() : buf(nullptr), bufe(nullptr)
392 * Write a single byte into the dumper.
393 * @param b The byte to write.
395 inline void WriteByte(byte b
)
397 /* Are we at the end of this chunk? */
398 if (this->buf
== this->bufe
) {
399 this->buf
= CallocT
<byte
>(MEMORY_CHUNK_SIZE
);
400 *this->blocks
.Append() = this->buf
;
401 this->bufe
= this->buf
+ MEMORY_CHUNK_SIZE
;
408 * Flush this dumper into a writer.
409 * @param writer The filter we want to use.
411 void Flush(SaveFilter
*writer
)
414 size_t t
= this->GetSize();
417 size_t to_write
= min(MEMORY_CHUNK_SIZE
, t
);
419 writer
->Write(this->blocks
[i
++], to_write
);
427 * Get the size of the memory dump made so far.
430 size_t GetSize() const
432 return this->blocks
.Length() * MEMORY_CHUNK_SIZE
- (this->bufe
- this->buf
);
436 /** The saveload struct, containing reader-writer functions, buffer, version, etc. */
437 struct SaveLoadParams
{
438 SaveLoadAction action
; ///< are we doing a save or a load atm.
439 NeedLength need_length
; ///< working in NeedLength (Autolength) mode?
440 byte block_mode
; ///< ???
441 bool error
; ///< did an error occur or not
443 size_t obj_len
; ///< the length of the current object we are busy with
444 int array_index
, last_array_index
; ///< in the case of an array, the current and last positions
446 MemoryDumper
*dumper
; ///< Memory dumper to write the savegame to.
447 SaveFilter
*sf
; ///< Filter to write the savegame to.
449 ReadBuffer
*reader
; ///< Savegame reading buffer.
450 LoadFilter
*lf
; ///< Filter to read the savegame from.
452 StringID error_str
; ///< the translatable error message to show
453 char *extra_msg
; ///< the error message
455 byte ff_state
; ///< The state of fast-forward when saving started.
456 bool saveinprogress
; ///< Whether there is currently a save in progress.
459 static SaveLoadParams _sl
; ///< Parameters used for/at saveload.
461 /* these define the chunks */
462 extern const ChunkHandler _gamelog_chunk_handlers
[];
463 extern const ChunkHandler _map_chunk_handlers
[];
464 extern const ChunkHandler _misc_chunk_handlers
[];
465 extern const ChunkHandler _name_chunk_handlers
[];
466 extern const ChunkHandler _cheat_chunk_handlers
[] ;
467 extern const ChunkHandler _setting_chunk_handlers
[];
468 extern const ChunkHandler _company_chunk_handlers
[];
469 extern const ChunkHandler _engine_chunk_handlers
[];
470 extern const ChunkHandler _veh_chunk_handlers
[];
471 extern const ChunkHandler _waypoint_chunk_handlers
[];
472 extern const ChunkHandler _depot_chunk_handlers
[];
473 extern const ChunkHandler _order_chunk_handlers
[];
474 extern const ChunkHandler _town_chunk_handlers
[];
475 extern const ChunkHandler _sign_chunk_handlers
[];
476 extern const ChunkHandler _station_chunk_handlers
[];
477 extern const ChunkHandler _industry_chunk_handlers
[];
478 extern const ChunkHandler _economy_chunk_handlers
[];
479 extern const ChunkHandler _subsidy_chunk_handlers
[];
480 extern const ChunkHandler _cargomonitor_chunk_handlers
[];
481 extern const ChunkHandler _goal_chunk_handlers
[];
482 extern const ChunkHandler _story_page_chunk_handlers
[];
483 extern const ChunkHandler _ai_chunk_handlers
[];
484 extern const ChunkHandler _game_chunk_handlers
[];
485 extern const ChunkHandler _animated_tile_chunk_handlers
[];
486 extern const ChunkHandler _newgrf_chunk_handlers
[];
487 extern const ChunkHandler _group_chunk_handlers
[];
488 extern const ChunkHandler _cargopacket_chunk_handlers
[];
489 extern const ChunkHandler _autoreplace_chunk_handlers
[];
490 extern const ChunkHandler _labelmaps_chunk_handlers
[];
491 extern const ChunkHandler _linkgraph_chunk_handlers
[];
492 extern const ChunkHandler _airport_chunk_handlers
[];
493 extern const ChunkHandler _object_chunk_handlers
[];
494 extern const ChunkHandler _persistent_storage_chunk_handlers
[];
495 extern const ChunkHandler _plan_chunk_handlers
[];
496 extern const ChunkHandler _trace_restrict_chunk_handlers
[];
497 extern const ChunkHandler _template_replacement_chunk_handlers
[];
498 extern const ChunkHandler _template_vehicle_chunk_handlers
[];
499 extern const ChunkHandler _logic_signal_handlers
[];
500 extern const ChunkHandler _bridge_signal_chunk_handlers
[];
501 extern const ChunkHandler _tunnel_chunk_handlers
[];
503 /** Array of all chunks in a savegame, \c nullptr terminated. */
504 static const ChunkHandler
* const _chunk_handlers
[] = {
505 _gamelog_chunk_handlers
,
507 _misc_chunk_handlers
,
508 _name_chunk_handlers
,
509 _cheat_chunk_handlers
,
510 _setting_chunk_handlers
,
512 _waypoint_chunk_handlers
,
513 _depot_chunk_handlers
,
514 _order_chunk_handlers
,
515 _industry_chunk_handlers
,
516 _economy_chunk_handlers
,
517 _subsidy_chunk_handlers
,
518 _cargomonitor_chunk_handlers
,
519 _goal_chunk_handlers
,
520 _story_page_chunk_handlers
,
521 _engine_chunk_handlers
,
522 _town_chunk_handlers
,
523 _sign_chunk_handlers
,
524 _station_chunk_handlers
,
525 _company_chunk_handlers
,
527 _game_chunk_handlers
,
528 _animated_tile_chunk_handlers
,
529 _newgrf_chunk_handlers
,
530 _group_chunk_handlers
,
531 _cargopacket_chunk_handlers
,
532 _autoreplace_chunk_handlers
,
533 _labelmaps_chunk_handlers
,
534 _linkgraph_chunk_handlers
,
535 _airport_chunk_handlers
,
536 _object_chunk_handlers
,
537 _persistent_storage_chunk_handlers
,
538 _plan_chunk_handlers
,
539 _trace_restrict_chunk_handlers
,
540 _template_replacement_chunk_handlers
,
541 _template_vehicle_chunk_handlers
,
542 _logic_signal_handlers
,
543 _bridge_signal_chunk_handlers
,
544 _tunnel_chunk_handlers
,
549 * Iterate over all chunk handlers.
550 * @param ch the chunk handler iterator
552 #define FOR_ALL_CHUNK_HANDLERS(ch) \
553 for (const ChunkHandler * const *chsc = _chunk_handlers; *chsc != nullptr; chsc++) \
554 for (const ChunkHandler *ch = *chsc; ch != nullptr; ch = (ch->flags & CH_LAST) ? nullptr : ch + 1)
556 /** Null all pointers (convert index -> nullptr) */
557 static void SlNullPointers()
559 _sl
.action
= SLA_NULL
;
561 /* We don't want any savegame conversion code to run
562 * during NULLing; especially those that try to get
563 * pointers from other pools. */
564 _sl_version
= SAVEGAME_VERSION
;
566 DEBUG(sl
, 1, "Nulling pointers");
568 FOR_ALL_CHUNK_HANDLERS(ch
) {
569 if (ch
->ptrs_proc
!= nullptr) {
570 DEBUG(sl
, 2, "Nulling pointers for %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
575 DEBUG(sl
, 1, "All pointers nulled");
577 assert(_sl
.action
== SLA_NULL
);
581 * Error handler. Sets everything up to show an error message and to clean
582 * up the mess of a partial savegame load.
583 * @param string The translatable error message to show.
584 * @param extra_msg An extra error message coming from one of the APIs.
585 * @note This function does never return as it throws an exception to
586 * break out of all the saveload code.
588 void NORETURN
SlError(StringID string
, const char *extra_msg
)
590 /* Distinguish between loading into _load_check_data vs. normal save/load. */
591 if (_sl
.action
== SLA_LOAD_CHECK
) {
592 _load_check_data
.error
= string
;
593 free(_load_check_data
.error_data
);
594 _load_check_data
.error_data
= (extra_msg
== nullptr) ? nullptr : stredup(extra_msg
);
596 _sl
.error_str
= string
;
598 _sl
.extra_msg
= (extra_msg
== nullptr) ? nullptr : stredup(extra_msg
);
601 /* We have to nullptr all pointers here; we might be in a state where
602 * the pointers are actually filled with indices, which means that
603 * when we access them during cleaning the pool dereferences of
604 * those indices will be made with segmentation faults as result. */
605 if (_sl
.action
== SLA_LOAD
|| _sl
.action
== SLA_PTRS
) SlNullPointers();
606 throw std::exception();
610 * Error handler for corrupt savegames. Sets everything up to show the
611 * error message and to clean up the mess of a partial savegame load.
612 * @param msg Location the corruption has been spotted.
613 * @note This function does never return as it throws an exception to
614 * break out of all the saveload code.
616 void NORETURN
SlErrorCorrupt(const char *msg
)
618 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME
, msg
);
622 typedef void (*AsyncSaveFinishProc
)(); ///< Callback for when the savegame loading is finished.
623 static AsyncSaveFinishProc _async_save_finish
= nullptr; ///< Callback to call when the savegame loading is finished.
624 static ThreadObject
*_save_thread
; ///< The thread we're using to compress and write a savegame
627 * Called by save thread to tell we finished saving.
628 * @param proc The callback to call when saving is done.
630 static void SetAsyncSaveFinish(AsyncSaveFinishProc proc
)
632 if (_exit_game
) return;
633 while (_async_save_finish
!= nullptr) CSleep(10);
635 _async_save_finish
= proc
;
639 * Handle async save finishes.
641 void ProcessAsyncSaveFinish()
643 if (_async_save_finish
== nullptr) return;
645 _async_save_finish();
647 _async_save_finish
= nullptr;
649 if (_save_thread
!= nullptr) {
650 _save_thread
->Join();
652 _save_thread
= nullptr;
657 * Wrapper for reading a byte from the buffer.
658 * @return The read byte.
662 return _sl
.reader
->ReadByte();
666 * Wrapper for writing a byte to the dumper.
667 * @param b The byte to write.
669 void SlWriteByte(byte b
)
671 _sl
.dumper
->WriteByte(b
);
674 static inline int SlReadUint16()
676 int x
= SlReadByte() << 8;
677 return x
| SlReadByte();
680 static inline uint32
SlReadUint32()
682 uint32 x
= SlReadUint16() << 16;
683 return x
| SlReadUint16();
686 static inline uint64
SlReadUint64()
688 uint32 x
= SlReadUint32();
689 uint32 y
= SlReadUint32();
690 return (uint64
)x
<< 32 | y
;
693 static inline void SlWriteUint16(uint16 v
)
695 SlWriteByte(GB(v
, 8, 8));
696 SlWriteByte(GB(v
, 0, 8));
699 static inline void SlWriteUint32(uint32 v
)
701 SlWriteUint16(GB(v
, 16, 16));
702 SlWriteUint16(GB(v
, 0, 16));
705 static inline void SlWriteUint64(uint64 x
)
707 SlWriteUint32((uint32
)(x
>> 32));
708 SlWriteUint32((uint32
)x
);
712 * Read in bytes from the file/data structure but don't do
713 * anything with them, discarding them in effect
714 * @param length The amount of bytes that is being treated this way
716 static inline void SlSkipBytes(size_t length
)
718 for (; length
!= 0; length
--) SlReadByte();
722 * Read in the header descriptor of an object or an array.
723 * If the highest bit is set (7), then the index is bigger than 127
724 * elements, so use the next byte to read in the real value.
725 * The actual value is then both bytes added with the first shifted
726 * 8 bits to the left, and dropping the highest bit (which only indicated a big index).
727 * x = ((x & 0x7F) << 8) + SlReadByte();
728 * @return Return the value of the index
730 static uint
SlReadSimpleGamma()
732 uint i
= SlReadByte();
742 SlErrorCorrupt("Unsupported gamma");
744 i
= SlReadByte(); // 32 bits only.
746 i
= (i
<< 8) | SlReadByte();
748 i
= (i
<< 8) | SlReadByte();
750 i
= (i
<< 8) | SlReadByte();
756 * Write the header descriptor of an object or an array.
757 * If the element is bigger than 127, use 2 bytes for saving
758 * and use the highest byte of the first written one as a notice
759 * that the length consists of 2 bytes, etc.. like this:
762 * 110xxxxx xxxxxxxx xxxxxxxx
763 * 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
764 * 11110--- xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
765 * We could extend the scheme ad infinum to support arbitrarily
766 * large chunks, but as sizeof(size_t) == 4 is still very common
767 * we don't support anything above 32 bits. That's why in the last
768 * case the 3 most significant bits are unused.
769 * @param i Index being written
772 static void SlWriteSimpleGamma(size_t i
)
775 if (i
>= (1 << 14)) {
776 if (i
>= (1 << 21)) {
777 if (i
>= (1 << 28)) {
778 assert(i
<= UINT32_MAX
); // We can only support 32 bits for now.
779 SlWriteByte((byte
)(0xF0));
780 SlWriteByte((byte
)(i
>> 24));
782 SlWriteByte((byte
)(0xE0 | (i
>> 24)));
784 SlWriteByte((byte
)(i
>> 16));
786 SlWriteByte((byte
)(0xC0 | (i
>> 16)));
788 SlWriteByte((byte
)(i
>> 8));
790 SlWriteByte((byte
)(0x80 | (i
>> 8)));
793 SlWriteByte((byte
)i
);
796 /** Return how many bytes used to encode a gamma value */
797 static inline uint
SlGetGammaLength(size_t i
)
799 return 1 + (i
>= (1 << 7)) + (i
>= (1 << 14)) + (i
>= (1 << 21)) + (i
>= (1 << 28));
802 static inline uint
SlReadSparseIndex()
804 return SlReadSimpleGamma();
807 static inline void SlWriteSparseIndex(uint index
)
809 SlWriteSimpleGamma(index
);
812 static inline uint
SlReadArrayLength()
814 return SlReadSimpleGamma();
817 static inline void SlWriteArrayLength(size_t length
)
819 SlWriteSimpleGamma(length
);
822 static inline uint
SlGetArrayLength(size_t length
)
824 return SlGetGammaLength(length
);
828 * Return the size in bytes of a certain type of normal/atomic variable
829 * as it appears in memory. See VarTypes
830 * @param conv VarType type of variable that is used for calculating the size
831 * @return Return the size of this type in bytes
833 static inline uint
SlCalcConvMemLen(VarType conv
)
835 static const byte conv_mem_size
[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
836 byte length
= GB(conv
, 4, 4);
838 switch (length
<< 4) {
843 return SlReadArrayLength();
846 assert(length
< lengthof(conv_mem_size
));
847 return conv_mem_size
[length
];
852 * Return the size in bytes of a certain type of normal/atomic variable
853 * as it appears in a saved game. See VarTypes
854 * @param conv VarType type of variable that is used for calculating the size
855 * @return Return the size of this type in bytes
857 static inline byte
SlCalcConvFileLen(VarType conv
)
859 static const byte conv_file_size
[] = {1, 1, 2, 2, 4, 4, 8, 8, 2};
860 byte length
= GB(conv
, 0, 4);
861 assert(length
< lengthof(conv_file_size
));
862 return conv_file_size
[length
];
865 /** Return the size in bytes of a reference (pointer) */
866 static inline size_t SlCalcRefLen()
868 return IsSavegameVersionBefore(69) ? 2 : 4;
871 void SlSetArrayIndex(uint index
)
873 _sl
.need_length
= NL_WANTLENGTH
;
874 _sl
.array_index
= index
;
877 static size_t _next_offs
;
880 * Iterate through the elements of an array and read the whole thing
881 * @return The index of the object, or -1 if we have reached the end of current block
887 /* After reading in the whole array inside the loop
888 * we must have read in all the data, so we must be at end of current block. */
889 if (_next_offs
!= 0 && _sl
.reader
->GetSize() != _next_offs
) SlErrorCorrupt("Invalid chunk size");
892 uint length
= SlReadArrayLength();
898 _sl
.obj_len
= --length
;
899 _next_offs
= _sl
.reader
->GetSize() + length
;
901 switch (_sl
.block_mode
) {
902 case CH_SPARSE_ARRAY
: index
= (int)SlReadSparseIndex(); break;
903 case CH_ARRAY
: index
= _sl
.array_index
++; break;
905 DEBUG(sl
, 0, "SlIterateArray error");
909 if (length
!= 0) return index
;
914 * Skip an array or sparse array
918 while (SlIterateArray() != -1) {
919 SlSkipBytes(_next_offs
- _sl
.reader
->GetSize());
924 * Sets the length of either a RIFF object or the number of items in an array.
925 * This lets us load an object or an array of arbitrary size
926 * @param length The length of the sought object/array
928 void SlSetLength(size_t length
)
930 assert(_sl
.action
== SLA_SAVE
);
932 switch (_sl
.need_length
) {
934 _sl
.need_length
= NL_NONE
;
935 switch (_sl
.block_mode
) {
937 /* Ugly encoding of >16M RIFF chunks
938 * The lower 24 bits are normal
939 * The uppermost 4 bits are bits 24:27 */
940 assert(length
< (1 << 28));
941 SlWriteUint32((uint32
)((length
& 0xFFFFFF) | ((length
>> 24) << 28)));
944 assert(_sl
.last_array_index
<= _sl
.array_index
);
945 while (++_sl
.last_array_index
<= _sl
.array_index
) {
946 SlWriteArrayLength(1);
948 SlWriteArrayLength(length
+ 1);
950 case CH_SPARSE_ARRAY
:
951 SlWriteArrayLength(length
+ 1 + SlGetArrayLength(_sl
.array_index
)); // Also include length of sparse index.
952 SlWriteSparseIndex(_sl
.array_index
);
954 default: NOT_REACHED();
959 _sl
.obj_len
+= (int)length
;
962 default: NOT_REACHED();
967 * Save/Load bytes. These do not need to be converted to Little/Big Endian
968 * so directly write them or read them to/from file
969 * @param ptr The source or destination of the object being manipulated
970 * @param length number of bytes this fast CopyBytes lasts
972 static void SlCopyBytes(void *ptr
, size_t length
)
974 byte
*p
= (byte
*)ptr
;
976 switch (_sl
.action
) {
979 for (; length
!= 0; length
--) *p
++ = SlReadByte();
982 for (; length
!= 0; length
--) SlWriteByte(*p
++);
984 default: NOT_REACHED();
988 /** Get the length of the current object */
989 size_t SlGetFieldLength()
995 * Return a signed-long version of the value of a setting
996 * @param ptr pointer to the variable
997 * @param conv type of variable, can be a non-clean
998 * type, eg one with other flags because it is parsed
999 * @return returns the value of the pointer-setting
1001 int64
ReadValue(const void *ptr
, VarType conv
)
1003 switch (GetVarMemType(conv
)) {
1004 case SLE_VAR_BL
: return (*(const bool *)ptr
!= 0);
1005 case SLE_VAR_I8
: return *(const int8
*)ptr
;
1006 case SLE_VAR_U8
: return *(const byte
*)ptr
;
1007 case SLE_VAR_I16
: return *(const int16
*)ptr
;
1008 case SLE_VAR_U16
: return *(const uint16
*)ptr
;
1009 case SLE_VAR_I32
: return *(const int32
*)ptr
;
1010 case SLE_VAR_U32
: return *(const uint32
*)ptr
;
1011 case SLE_VAR_I64
: return *(const int64
*)ptr
;
1012 case SLE_VAR_U64
: return *(const uint64
*)ptr
;
1013 case SLE_VAR_NULL
:return 0;
1014 default: NOT_REACHED();
1019 * Write the value of a setting
1020 * @param ptr pointer to the variable
1021 * @param conv type of variable, can be a non-clean type, eg
1022 * with other flags. It is parsed upon read
1023 * @param val the new value being given to the variable
1025 void WriteValue(void *ptr
, VarType conv
, int64 val
)
1027 switch (GetVarMemType(conv
)) {
1028 case SLE_VAR_BL
: *(bool *)ptr
= (val
!= 0); break;
1029 case SLE_VAR_I8
: *(int8
*)ptr
= val
; break;
1030 case SLE_VAR_U8
: *(byte
*)ptr
= val
; break;
1031 case SLE_VAR_I16
: *(int16
*)ptr
= val
; break;
1032 case SLE_VAR_U16
: *(uint16
*)ptr
= val
; break;
1033 case SLE_VAR_I32
: *(int32
*)ptr
= val
; break;
1034 case SLE_VAR_U32
: *(uint32
*)ptr
= val
; break;
1035 case SLE_VAR_I64
: *(int64
*)ptr
= val
; break;
1036 case SLE_VAR_U64
: *(uint64
*)ptr
= val
; break;
1037 case SLE_VAR_NAME
: *(char**)ptr
= CopyFromOldName(val
); break;
1038 case SLE_VAR_NULL
: break;
1039 default: NOT_REACHED();
1044 * Handle all conversion and typechecking of variables here.
1045 * In the case of saving, read in the actual value from the struct
1046 * and then write them to file, endian safely. Loading a value
1047 * goes exactly the opposite way
1048 * @param ptr The object being filled/read
1049 * @param conv VarType type of the current element of the struct
1051 static void SlSaveLoadConv(void *ptr
, VarType conv
)
1053 switch (_sl
.action
) {
1055 int64 x
= ReadValue(ptr
, conv
);
1057 /* Write the value to the file and check if its value is in the desired range */
1058 switch (GetVarFileType(conv
)) {
1059 case SLE_FILE_I8
: assert(x
>= -128 && x
<= 127); SlWriteByte(x
);break;
1060 case SLE_FILE_U8
: assert(x
>= 0 && x
<= 255); SlWriteByte(x
);break;
1061 case SLE_FILE_I16
:assert(x
>= -32768 && x
<= 32767); SlWriteUint16(x
);break;
1062 case SLE_FILE_STRINGID
:
1063 case SLE_FILE_U16
:assert(x
>= 0 && x
<= 65535); SlWriteUint16(x
);break;
1065 case SLE_FILE_U32
: SlWriteUint32((uint32
)x
);break;
1067 case SLE_FILE_U64
: SlWriteUint64(x
);break;
1068 default: NOT_REACHED();
1072 case SLA_LOAD_CHECK
:
1075 /* Read a value from the file */
1076 switch (GetVarFileType(conv
)) {
1077 case SLE_FILE_I8
: x
= (int8
)SlReadByte(); break;
1078 case SLE_FILE_U8
: x
= (byte
)SlReadByte(); break;
1079 case SLE_FILE_I16
: x
= (int16
)SlReadUint16(); break;
1080 case SLE_FILE_U16
: x
= (uint16
)SlReadUint16(); break;
1081 case SLE_FILE_I32
: x
= (int32
)SlReadUint32(); break;
1082 case SLE_FILE_U32
: x
= (uint32
)SlReadUint32(); break;
1083 case SLE_FILE_I64
: x
= (int64
)SlReadUint64(); break;
1084 case SLE_FILE_U64
: x
= (uint64
)SlReadUint64(); break;
1085 case SLE_FILE_STRINGID
: x
= RemapOldStringID((uint16
)SlReadUint16()); break;
1086 default: NOT_REACHED();
1089 /* Write The value to the struct. These ARE endian safe. */
1090 WriteValue(ptr
, conv
, x
);
1093 case SLA_PTRS
: break;
1094 case SLA_NULL
: break;
1095 default: NOT_REACHED();
1100 * Calculate the net length of a string. This is in almost all cases
1101 * just strlen(), but if the string is not properly terminated, we'll
1102 * resort to the maximum length of the buffer.
1103 * @param ptr pointer to the stringbuffer
1104 * @param length maximum length of the string (buffer). If -1 we don't care
1105 * about a maximum length, but take string length as it is.
1106 * @return return the net length of the string
1108 static inline size_t SlCalcNetStringLen(const char *ptr
, size_t length
)
1110 if (ptr
== nullptr) return 0;
1111 return min(strlen(ptr
), length
- 1);
1115 * Calculate the gross length of the std::string that it
1116 * will occupy in the savegame. This includes the real length,
1117 * and the length that the index will occupy.
1118 * @param str reference to the std::string
1119 * @return return the gross length of the string
1121 static inline size_t SlCalcStdStrLen(const std::string
&str
)
1123 return str
.size() + SlGetArrayLength(str
.size()); // also include the length of the index
1127 * Calculate the gross length of the string that it
1128 * will occupy in the savegame. This includes the real length, returned
1129 * by SlCalcNetStringLen and the length that the index will occupy.
1130 * @param ptr pointer to the stringbuffer
1131 * @param length maximum length of the string (buffer size, etc.)
1132 * @param conv type of data been used
1133 * @return return the gross length of the string
1135 static inline size_t SlCalcStringLen(const void *ptr
, size_t length
, VarType conv
)
1140 switch (GetVarMemType(conv
)) {
1141 default: NOT_REACHED();
1144 str
= *(const char * const *)ptr
;
1149 str
= (const char *)ptr
;
1154 len
= SlCalcNetStringLen(str
, len
);
1155 return len
+ SlGetArrayLength(len
); // also include the length of the index
1159 * Save/Load a string.
1160 * @param ptr the string being manipulated
1161 * @param length of the string (full length)
1162 * @param conv must be SLE_FILE_STRING
1164 static void SlString(void *ptr
, size_t length
, VarType conv
)
1166 switch (_sl
.action
) {
1169 switch (GetVarMemType(conv
)) {
1170 default: NOT_REACHED();
1173 len
= SlCalcNetStringLen((char *)ptr
, length
);
1177 ptr
= *(char **)ptr
;
1178 len
= SlCalcNetStringLen((char *)ptr
, SIZE_MAX
);
1182 SlWriteArrayLength(len
);
1183 SlCopyBytes(ptr
, len
);
1186 case SLA_LOAD_CHECK
:
1188 size_t len
= SlReadArrayLength();
1190 switch (GetVarMemType(conv
)) {
1191 default: NOT_REACHED();
1194 if (len
>= length
) {
1195 DEBUG(sl
, 1, "String length in savegame is bigger than buffer, truncating");
1196 SlCopyBytes(ptr
, length
);
1197 SlSkipBytes(len
- length
);
1200 SlCopyBytes(ptr
, len
);
1204 case SLE_VAR_STRQ
: // Malloc'd string, free previous incarnation, and allocate
1205 free(*(char **)ptr
);
1207 *(char **)ptr
= nullptr;
1210 *(char **)ptr
= MallocT
<char>(len
+ 1); // terminating '\0'
1211 ptr
= *(char **)ptr
;
1212 SlCopyBytes(ptr
, len
);
1217 ((char *)ptr
)[len
] = '\0'; // properly terminate the string
1218 StringValidationSettings settings
= SVS_REPLACE_WITH_QUESTION_MARK
;
1219 if ((conv
& SLF_ALLOW_CONTROL
) != 0) {
1220 settings
= settings
| SVS_ALLOW_CONTROL_CODE
;
1221 if (IsSavegameVersionBefore(169)) {
1222 str_fix_scc_encoded((char *)ptr
, (char *)ptr
+ len
);
1225 if ((conv
& SLF_ALLOW_NEWLINE
) != 0) {
1226 settings
= settings
| SVS_ALLOW_NEWLINE
;
1228 str_validate((char *)ptr
, (char *)ptr
+ len
, settings
);
1231 case SLA_PTRS
: break;
1232 case SLA_NULL
: break;
1233 default: NOT_REACHED();
1238 * Save/Load a std::string.
1239 * @param ptr the std::string being manipulated
1240 * @param conv must be SLE_FILE_STRING
1242 static void SlStdString(std::string
&str
, VarType conv
)
1244 switch (_sl
.action
) {
1246 SlWriteArrayLength(str
.size());
1247 SlCopyBytes(const_cast<char *>(str
.data()), str
.size());
1250 case SLA_LOAD_CHECK
:
1252 size_t len
= SlReadArrayLength();
1254 SlCopyBytes(const_cast<char *>(str
.c_str()), len
);
1256 StringValidationSettings settings
= SVS_REPLACE_WITH_QUESTION_MARK
;
1257 if ((conv
& SLF_ALLOW_CONTROL
) != 0) {
1258 settings
= settings
| SVS_ALLOW_CONTROL_CODE
;
1260 if ((conv
& SLF_ALLOW_NEWLINE
) != 0) {
1261 settings
= settings
| SVS_ALLOW_NEWLINE
;
1263 str_validate(str
, settings
);
1266 case SLA_PTRS
: break;
1267 case SLA_NULL
: break;
1268 default: NOT_REACHED();
1273 * Return the size in bytes of a certain type of atomic array
1274 * @param length The length of the array counted in elements
1275 * @param conv VarType type of the variable that is used in calculating the size
1277 static inline size_t SlCalcArrayLen(size_t length
, VarType conv
)
1279 return SlCalcConvFileLen(conv
) * length
;
1283 * Save/Load an array.
1284 * @param array The array being manipulated
1285 * @param length The length of the array in elements
1286 * @param conv VarType type of the atomic array (int, byte, uint64, etc.)
1288 void SlArray(void *array
, size_t length
, VarType conv
)
1290 if (_sl
.action
== SLA_PTRS
|| _sl
.action
== SLA_NULL
) return;
1292 /* Automatically calculate the length? */
1293 if (_sl
.need_length
!= NL_NONE
) {
1294 SlSetLength(SlCalcArrayLen(length
, conv
));
1295 /* Determine length only? */
1296 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1299 /* NOTICE - handle some buggy stuff, in really old versions everything was saved
1300 * as a byte-type. So detect this, and adjust array size accordingly */
1301 if (_sl
.action
!= SLA_SAVE
&& _sl_version
== 0) {
1302 /* all arrays except difficulty settings */
1303 if (conv
== SLE_INT16
|| conv
== SLE_UINT16
|| conv
== SLE_STRINGID
||
1304 conv
== SLE_INT32
|| conv
== SLE_UINT32
) {
1305 SlCopyBytes(array
, length
* SlCalcConvFileLen(conv
));
1308 /* used for conversion of Money 32bit->64bit */
1309 if (conv
== (SLE_FILE_I32
| SLE_VAR_I64
)) {
1310 for (uint i
= 0; i
< length
; i
++) {
1311 ((int64
*)array
)[i
] = (int32
)BSWAP32(SlReadUint32());
1317 /* If the size of elements is 1 byte both in file and memory, no special
1318 * conversion is needed, use specialized copy-copy function to speed up things */
1319 if (conv
== SLE_INT8
|| conv
== SLE_UINT8
) {
1320 SlCopyBytes(array
, length
);
1322 byte
*a
= (byte
*)array
;
1323 byte mem_size
= SlCalcConvMemLen(conv
);
1325 for (; length
!= 0; length
--) {
1326 SlSaveLoadConv(a
, conv
);
1327 a
+= mem_size
; // get size
1334 * Pointers cannot be saved to a savegame, so this functions gets
1335 * the index of the item, and if not available, it hussles with
1336 * pointers (looks really bad :()
1337 * Remember that a nullptr item has value 0, and all
1338 * indices have +1, so vehicle 0 is saved as index 1.
1339 * @param obj The object that we want to get the index of
1340 * @param rt SLRefType type of the object the index is being sought of
1341 * @return Return the pointer converted to an index of the type pointed to
1343 static size_t ReferenceToInt(const void *obj
, SLRefType rt
)
1345 assert(_sl
.action
== SLA_SAVE
);
1347 if (obj
== nullptr) return 0;
1350 case REF_VEHICLE_OLD
: // Old vehicles we save as new ones
1351 case REF_VEHICLE
: return ((const Vehicle
*)obj
)->index
+ 1;
1352 case REF_TEMPLATE_VEHICLE
: return ((const TemplateVehicle
*)obj
)->index
+ 1;
1353 case REF_STATION
: return ((const Station
*)obj
)->index
+ 1;
1354 case REF_TOWN
: return ((const Town
*)obj
)->index
+ 1;
1355 case REF_ORDER
: return ((const Order
*)obj
)->index
+ 1;
1356 case REF_ROADSTOPS
: return ((const RoadStop
*)obj
)->index
+ 1;
1357 case REF_ENGINE_RENEWS
: return ((const EngineRenew
*)obj
)->index
+ 1;
1358 case REF_CARGO_PACKET
: return ((const CargoPacket
*)obj
)->index
+ 1;
1359 case REF_ORDERLIST
: return ((const OrderList
*)obj
)->index
+ 1;
1360 case REF_STORAGE
: return ((const PersistentStorage
*)obj
)->index
+ 1;
1361 case REF_LINK_GRAPH
: return ((const LinkGraph
*)obj
)->index
+ 1;
1362 case REF_LINK_GRAPH_JOB
: return ((const LinkGraphJob
*)obj
)->index
+ 1;
1363 case REF_DOCKS
: return ((const Dock
*)obj
)->index
+ 1;
1364 default: NOT_REACHED();
1369 * Pointers cannot be loaded from a savegame, so this function
1370 * gets the index from the savegame and returns the appropriate
1371 * pointer from the already loaded base.
1372 * Remember that an index of 0 is a nullptr pointer so all indices
1373 * are +1 so vehicle 0 is saved as 1.
1374 * @param index The index that is being converted to a pointer
1375 * @param rt SLRefType type of the object the pointer is sought of
1376 * @return Return the index converted to a pointer of any type
1378 static void *IntToReference(size_t index
, SLRefType rt
)
1380 assert_compile(sizeof(size_t) <= sizeof(void *));
1382 assert(_sl
.action
== SLA_PTRS
);
1384 /* After version 4.3 REF_VEHICLE_OLD is saved as REF_VEHICLE,
1385 * and should be loaded like that */
1386 if (rt
== REF_VEHICLE_OLD
&& !IsSavegameVersionBefore(4, 4)) {
1390 /* No need to look up nullptr pointers, just return immediately */
1391 if (index
== (rt
== REF_VEHICLE_OLD
? 0xFFFF : 0)) return nullptr;
1393 /* Correct index. Old vehicles were saved differently:
1394 * invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
1395 if (rt
!= REF_VEHICLE_OLD
) index
--;
1399 if (OrderList::IsValidID(index
)) return OrderList::Get(index
);
1400 SlErrorCorrupt("Referencing invalid OrderList");
1403 if (Order::IsValidID(index
)) return Order::Get(index
);
1404 /* in old versions, invalid order was used to mark end of order list */
1405 if (IsSavegameVersionBefore(5, 2)) return nullptr;
1406 SlErrorCorrupt("Referencing invalid Order");
1408 case REF_VEHICLE_OLD
:
1410 if (Vehicle::IsValidID(index
)) return Vehicle::Get(index
);
1411 SlErrorCorrupt("Referencing invalid Vehicle");
1413 case REF_TEMPLATE_VEHICLE
:
1414 if (TemplateVehicle::IsValidID(index
)) return TemplateVehicle::Get(index
);
1415 SlErrorCorrupt("Referencing invalid TemplateVehicle");
1418 if (Station::IsValidID(index
)) return Station::Get(index
);
1419 SlErrorCorrupt("Referencing invalid Station");
1422 if (Town::IsValidID(index
)) return Town::Get(index
);
1423 SlErrorCorrupt("Referencing invalid Town");
1426 if (RoadStop::IsValidID(index
)) return RoadStop::Get(index
);
1427 SlErrorCorrupt("Referencing invalid RoadStop");
1430 if (Dock::IsValidID(index
)) return Dock::Get(index
);
1431 SlErrorCorrupt("Referencing invalid Dock");
1433 case REF_ENGINE_RENEWS
:
1434 if (EngineRenew::IsValidID(index
)) return EngineRenew::Get(index
);
1435 SlErrorCorrupt("Referencing invalid EngineRenew");
1437 case REF_CARGO_PACKET
:
1438 if (CargoPacket::IsValidID(index
)) return CargoPacket::Get(index
);
1439 SlErrorCorrupt("Referencing invalid CargoPacket");
1442 if (PersistentStorage::IsValidID(index
)) return PersistentStorage::Get(index
);
1443 SlErrorCorrupt("Referencing invalid PersistentStorage");
1445 case REF_LINK_GRAPH
:
1446 if (LinkGraph::IsValidID(index
)) return LinkGraph::Get(index
);
1447 SlErrorCorrupt("Referencing invalid LinkGraph");
1449 case REF_LINK_GRAPH_JOB
:
1450 if (LinkGraphJob::IsValidID(index
)) return LinkGraphJob::Get(index
);
1451 SlErrorCorrupt("Referencing invalid LinkGraphJob");
1453 default: NOT_REACHED();
1458 * Return the size in bytes of a list
1459 * @param list The std::list to find the size of
1461 template<typename PtrList
>
1462 static inline size_t SlCalcListLen(const void *list
)
1464 const PtrList
*l
= (const PtrList
*)list
;
1466 int type_size
= IsSavegameVersionBefore(69) ? 2 : 4;
1467 /* Each entry is saved as type_size bytes, plus type_size bytes are used for the length
1469 return l
->size() * type_size
+ type_size
;
1473 * Return the size in bytes of a list
1474 * @param list The std::list to find the size of
1476 template<typename PtrList
>
1477 static inline size_t SlCalcVarListLen(const void *list
, size_t item_size
)
1479 const PtrList
*l
= (const PtrList
*) list
;
1480 /* Each entry is saved as item_size bytes, plus 4 bytes are used for the length
1482 return l
->size() * item_size
+ 4;
1488 * @param list The list being manipulated
1489 * @param conv SLRefType type of the list (Vehicle *, Station *, etc)
1491 template<typename PtrList
>
1492 static void SlList(void *list
, SLRefType conv
)
1494 /* Automatically calculate the length? */
1495 if (_sl
.need_length
!= NL_NONE
) {
1496 SlSetLength(SlCalcListLen
<PtrList
>(list
));
1497 /* Determine length only? */
1498 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1501 PtrList
*l
= (PtrList
*)list
;
1503 switch (_sl
.action
) {
1505 SlWriteUint32((uint32
)l
->size());
1507 typename
PtrList::iterator iter
;
1508 for (iter
= l
->begin(); iter
!= l
->end(); ++iter
) {
1510 SlWriteUint32((uint32
)ReferenceToInt(ptr
, conv
));
1514 case SLA_LOAD_CHECK
:
1516 size_t length
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1518 /* Load each reference and push to the end of the list */
1519 for (size_t i
= 0; i
< length
; i
++) {
1520 size_t data
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1521 l
->push_back((void *)data
);
1529 typename
PtrList::iterator iter
;
1530 for (iter
= temp
.begin(); iter
!= temp
.end(); ++iter
) {
1531 void *ptr
= IntToReference((size_t)*iter
, conv
);
1539 default: NOT_REACHED();
1545 * @param list The list being manipulated
1546 * @param conv VarType type of the list
1548 template<typename PtrList
>
1549 static void SlVarList(void *list
, VarType conv
)
1551 const size_t size_len
= SlCalcConvMemLen(conv
);
1552 /* Automatically calculate the length? */
1553 if (_sl
.need_length
!= NL_NONE
) {
1554 SlSetLength(SlCalcVarListLen
<PtrList
>(list
, size_len
));
1555 /* Determine length only? */
1556 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1559 PtrList
*l
= (PtrList
*)list
;
1561 switch (_sl
.action
) {
1563 SlWriteUint32((uint32
)l
->size());
1565 typename
PtrList::iterator iter
;
1566 for (iter
= l
->begin(); iter
!= l
->end(); ++iter
) {
1567 SlSaveLoadConv(&(*iter
), conv
);
1571 case SLA_LOAD_CHECK
:
1573 size_t length
= SlReadUint32();
1576 typename
PtrList::iterator iter
;
1579 for (size_t i
= 0; i
< length
; i
++) {
1580 SlSaveLoadConv(&(*iter
), conv
);
1585 case SLA_PTRS
: break;
1589 default: NOT_REACHED();
1594 /** Are we going to save this object or not? */
1595 static inline bool SlIsObjectValidInSavegame(const SaveLoad
*sld
)
1597 if (_sl_version
< sld
->version_from
|| _sl_version
> sld
->version_to
) return false;
1598 if (sld
->conv
& SLF_NOT_IN_SAVE
) return false;
1604 * Are we going to load this variable when loading a savegame or not?
1605 * @note If the variable is skipped it is skipped in the savegame
1606 * bytestream itself as well, so there is no need to skip it somewhere else
1608 static inline bool SlSkipVariableOnLoad(const SaveLoad
*sld
)
1610 if ((sld
->conv
& SLF_NO_NETWORK_SYNC
) && _sl
.action
!= SLA_SAVE
&& _networking
&& !_network_server
) {
1611 SlSkipBytes(SlCalcConvMemLen(sld
->conv
) * sld
->length
);
1619 * Calculate the size of an object.
1620 * @param object to be measured
1621 * @param sld The SaveLoad description of the object so we know how to manipulate it
1622 * @return size of given object
1624 size_t SlCalcObjLength(const void *object
, const SaveLoad
*sld
)
1628 /* Need to determine the length and write a length tag. */
1629 for (; sld
->cmd
!= SL_END
; sld
++) {
1630 length
+= SlCalcObjMemberLength(object
, sld
);
1635 size_t SlCalcObjMemberLength(const void *object
, const SaveLoad
*sld
)
1637 assert(_sl
.action
== SLA_SAVE
);
1649 /* CONDITIONAL saveload types depend on the savegame version */
1650 if (!SlIsObjectValidInSavegame(sld
)) break;
1653 case SL_VAR
: return SlCalcConvFileLen(sld
->conv
);
1654 case SL_REF
: return SlCalcRefLen();
1655 case SL_ARR
: return SlCalcArrayLen(sld
->length
, sld
->conv
);
1656 case SL_STR
: return SlCalcStringLen(GetVariableAddress(object
, sld
), sld
->length
, sld
->conv
);
1657 case SL_LST
: return SlCalcListLen
<std::list
<void *>>(GetVariableAddress(object
, sld
));
1658 case SL_DEQ
: return SlCalcListLen
<std::deque
<void *>>(GetVariableAddress(object
, sld
));
1659 case SL_VEC
: return SlCalcListLen
<std::vector
<void *>>(GetVariableAddress(object
, sld
));
1661 const size_t size_len
= SlCalcConvMemLen(sld
->conv
);
1663 case 1: return SlCalcVarListLen
<std::vector
<byte
>>(GetVariableAddress(object
, sld
), 1);
1664 case 2: return SlCalcVarListLen
<std::vector
<uint16
>>(GetVariableAddress(object
, sld
), 2);
1665 case 4: return SlCalcVarListLen
<std::vector
<uint32
>>(GetVariableAddress(object
, sld
), 4);
1666 case 8: return SlCalcVarListLen
<std::vector
<uint64
>>(GetVariableAddress(object
, sld
), 8);
1667 default: NOT_REACHED();
1670 case SL_STDSTR
: return SlCalcStdStrLen(*static_cast<std::string
*>(GetVariableAddress(object
, sld
)));
1671 default: NOT_REACHED();
1674 case SL_WRITEBYTE
: return 1; // a byte is logically of size 1
1675 case SL_VEH_INCLUDE
: return SlCalcObjLength(object
, GetVehicleDescription(VEH_END
));
1676 case SL_ST_INCLUDE
: return SlCalcObjLength(object
, GetBaseStationDescription());
1677 default: NOT_REACHED();
1685 * Check whether the variable size of the variable in the saveload configuration
1686 * matches with the actual variable size.
1687 * @param sld The saveload configuration to test.
1689 static bool IsVariableSizeRight(const SaveLoad
*sld
)
1693 switch (GetVarMemType(sld
->conv
)) {
1695 return sld
->size
== sizeof(bool);
1698 return sld
->size
== sizeof(int8
);
1701 return sld
->size
== sizeof(int16
);
1704 return sld
->size
== sizeof(int32
);
1707 return sld
->size
== sizeof(int64
);
1709 return sld
->size
== sizeof(void *);
1712 /* These should all be pointer sized. */
1713 return sld
->size
== sizeof(void *);
1716 /* These should be pointer sized, or fixed array. */
1717 return sld
->size
== sizeof(void *) || sld
->size
== sld
->length
;
1720 return sld
->size
== sizeof(std::string
);
1727 #endif /* OTTD_ASSERT */
1729 bool SlObjectMember(void *ptr
, const SaveLoad
*sld
)
1732 assert(IsVariableSizeRight(sld
));
1735 VarType conv
= GB(sld
->conv
, 0, 8);
1746 /* CONDITIONAL saveload types depend on the savegame version */
1747 if (!SlIsObjectValidInSavegame(sld
)) return false;
1748 if (SlSkipVariableOnLoad(sld
)) return false;
1751 case SL_VAR
: SlSaveLoadConv(ptr
, conv
); break;
1752 case SL_REF
: // Reference variable, translate
1753 switch (_sl
.action
) {
1755 SlWriteUint32((uint32
)ReferenceToInt(*(void **)ptr
, (SLRefType
)conv
));
1757 case SLA_LOAD_CHECK
:
1759 *(size_t *)ptr
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1762 *(void **)ptr
= IntToReference(*(size_t *)ptr
, (SLRefType
)conv
);
1765 *(void **)ptr
= nullptr;
1767 default: NOT_REACHED();
1770 case SL_ARR
: SlArray(ptr
, sld
->length
, conv
); break;
1771 case SL_STR
: SlString(ptr
, sld
->length
, sld
->conv
); break;
1772 case SL_LST
: SlList
<std::list
<void *>>(ptr
, (SLRefType
)conv
); break;
1773 case SL_DEQ
: SlList
<std::deque
<void *>>(ptr
, (SLRefType
)conv
); break;
1774 case SL_VEC
: SlList
<std::vector
<void *>>(ptr
, (SLRefType
)conv
); break;
1776 const size_t size_len
= SlCalcConvMemLen(sld
->conv
);
1778 case 1: SlVarList
<std::vector
<byte
>>(ptr
, conv
); break;
1779 case 2: SlVarList
<std::vector
<uint16
>>(ptr
, conv
); break;
1780 case 4: SlVarList
<std::vector
<uint32
>>(ptr
, conv
); break;
1781 case 8: SlVarList
<std::vector
<uint64
>>(ptr
, conv
); break;
1782 default: NOT_REACHED();
1786 case SL_STDSTR
: SlStdString(*static_cast<std::string
*>(ptr
), sld
->conv
); break;
1787 default: NOT_REACHED();
1791 /* SL_WRITEBYTE translates a value of a variable to another one upon
1792 * saving or loading.
1793 * XXX - variable renaming abuse
1794 * game_value: the value of the variable ingame is abused by sld->version_from
1795 * file_value: the value of the variable in the savegame is abused by sld->version_to */
1797 switch (_sl
.action
) {
1798 case SLA_SAVE
: SlWriteByte(sld
->version_to
); break;
1799 case SLA_LOAD_CHECK
:
1800 case SLA_LOAD
: *(byte
*)ptr
= sld
->version_from
; break;
1801 case SLA_PTRS
: break;
1802 case SLA_NULL
: break;
1803 default: NOT_REACHED();
1807 /* SL_VEH_INCLUDE loads common code for vehicles */
1808 case SL_VEH_INCLUDE
:
1809 SlObject(ptr
, GetVehicleDescription(VEH_END
));
1813 SlObject(ptr
, GetBaseStationDescription());
1816 default: NOT_REACHED();
1822 * Main SaveLoad function.
1823 * @param object The object that is being saved or loaded
1824 * @param sld The SaveLoad description of the object so we know how to manipulate it
1826 void SlObject(void *object
, const SaveLoad
*sld
)
1828 /* Automatically calculate the length? */
1829 if (_sl
.need_length
!= NL_NONE
) {
1830 SlSetLength(SlCalcObjLength(object
, sld
));
1831 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1834 for (; sld
->cmd
!= SL_END
; sld
++) {
1835 void *ptr
= sld
->global
? sld
->address
: GetVariableAddress(object
, sld
);
1836 SlObjectMember(ptr
, sld
);
1841 * Save or Load (a list of) global variables
1842 * @param sldg The global variable that is being loaded or saved
1844 void SlGlobList(const SaveLoadGlobVarList
*sldg
)
1846 SlObject(nullptr, (const SaveLoad
*)sldg
);
1850 * Do something of which I have no idea what it is :P
1851 * @param proc The callback procedure that is called
1852 * @param arg The variable that will be used for the callback procedure
1854 void SlAutolength(AutolengthProc
*proc
, void *arg
)
1858 assert(_sl
.action
== SLA_SAVE
);
1860 /* Tell it to calculate the length */
1861 _sl
.need_length
= NL_CALCLENGTH
;
1866 _sl
.need_length
= NL_WANTLENGTH
;
1867 SlSetLength(_sl
.obj_len
);
1869 offs
= _sl
.dumper
->GetSize() + _sl
.obj_len
;
1871 /* And write the stuff */
1874 if (offs
!= _sl
.dumper
->GetSize()) SlErrorCorrupt("Invalid chunk size");
1878 * Load a chunk of data (eg vehicles, stations, etc.)
1879 * @param ch The chunkhandler that will be used for the operation
1881 static void SlLoadChunk(const ChunkHandler
*ch
)
1883 byte m
= SlReadByte();
1892 _sl
.array_index
= 0;
1894 if (_next_offs
!= 0) SlErrorCorrupt("Invalid array length");
1896 case CH_SPARSE_ARRAY
:
1898 if (_next_offs
!= 0) SlErrorCorrupt("Invalid array length");
1901 if ((m
& 0xF) == CH_RIFF
) {
1903 len
= (SlReadByte() << 16) | ((m
>> 4) << 24);
1904 len
+= SlReadUint16();
1906 endoffs
= _sl
.reader
->GetSize() + len
;
1908 if (_sl
.reader
->GetSize() != endoffs
) SlErrorCorrupt("Invalid chunk size");
1910 SlErrorCorrupt("Invalid chunk type");
1917 * Load a chunk of data for checking savegames.
1918 * If the chunkhandler is nullptr, the chunk is skipped.
1919 * @param ch The chunkhandler that will be used for the operation
1921 static void SlLoadCheckChunk(const ChunkHandler
*ch
)
1923 byte m
= SlReadByte();
1932 _sl
.array_index
= 0;
1933 if (ch
->load_check_proc
) {
1934 ch
->load_check_proc();
1939 case CH_SPARSE_ARRAY
:
1940 if (ch
->load_check_proc
) {
1941 ch
->load_check_proc();
1947 if ((m
& 0xF) == CH_RIFF
) {
1949 len
= (SlReadByte() << 16) | ((m
>> 4) << 24);
1950 len
+= SlReadUint16();
1952 endoffs
= _sl
.reader
->GetSize() + len
;
1953 if (ch
->load_check_proc
) {
1954 ch
->load_check_proc();
1958 if (_sl
.reader
->GetSize() != endoffs
) SlErrorCorrupt("Invalid chunk size");
1960 SlErrorCorrupt("Invalid chunk type");
1967 * Save a chunk of data (eg. vehicles, stations, etc.). Each chunk is
1968 * prefixed by an ID identifying it, followed by data, and terminator where appropriate
1969 * @param ch The chunkhandler that will be used for the operation
1971 static void SlSaveChunk(const ChunkHandler
*ch
)
1973 ChunkSaveLoadProc
*proc
= ch
->save_proc
;
1975 /* Don't save any chunk information if there is no save handler. */
1976 if (proc
== nullptr) return;
1978 SlWriteUint32(ch
->id
);
1979 DEBUG(sl
, 2, "Saving chunk %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
1981 _sl
.block_mode
= ch
->flags
& CH_TYPE_MASK
;
1982 switch (ch
->flags
& CH_TYPE_MASK
) {
1984 _sl
.need_length
= NL_WANTLENGTH
;
1988 _sl
.last_array_index
= 0;
1989 SlWriteByte(CH_ARRAY
);
1991 SlWriteArrayLength(0); // Terminate arrays
1993 case CH_SPARSE_ARRAY
:
1994 SlWriteByte(CH_SPARSE_ARRAY
);
1996 SlWriteArrayLength(0); // Terminate arrays
1998 default: NOT_REACHED();
2002 /** Save all chunks */
2003 static void SlSaveChunks()
2005 FOR_ALL_CHUNK_HANDLERS(ch
) {
2014 * Find the ChunkHandler that will be used for processing the found
2015 * chunk in the savegame or in memory
2016 * @param id the chunk in question
2017 * @return returns the appropriate chunkhandler
2019 static const ChunkHandler
*SlFindChunkHandler(uint32 id
)
2021 FOR_ALL_CHUNK_HANDLERS(ch
) if (ch
->id
== id
) return ch
;
2025 /** Load all chunks */
2026 static void SlLoadChunks()
2029 const ChunkHandler
*ch
;
2031 for (id
= SlReadUint32(); id
!= 0; id
= SlReadUint32()) {
2032 DEBUG(sl
, 2, "Loading chunk %c%c%c%c", id
>> 24, id
>> 16, id
>> 8, id
);
2034 ch
= SlFindChunkHandler(id
);
2035 if (ch
== nullptr) SlErrorCorrupt("Unknown chunk type");
2040 /** Load all chunks for savegame checking */
2041 static void SlLoadCheckChunks()
2044 const ChunkHandler
*ch
;
2046 for (id
= SlReadUint32(); id
!= 0; id
= SlReadUint32()) {
2047 DEBUG(sl
, 2, "Loading chunk %c%c%c%c", id
>> 24, id
>> 16, id
>> 8, id
);
2049 ch
= SlFindChunkHandler(id
);
2050 if (ch
== nullptr) SlErrorCorrupt("Unknown chunk type");
2051 SlLoadCheckChunk(ch
);
2055 /** Fix all pointers (convert index -> pointer) */
2056 static void SlFixPointers()
2058 _sl
.action
= SLA_PTRS
;
2060 DEBUG(sl
, 1, "Fixing pointers");
2062 FOR_ALL_CHUNK_HANDLERS(ch
) {
2063 if (ch
->ptrs_proc
!= nullptr) {
2064 DEBUG(sl
, 2, "Fixing pointers for %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
2069 DEBUG(sl
, 1, "All pointers fixed");
2071 assert(_sl
.action
== SLA_PTRS
);
2075 /** Yes, simply reading from a file. */
2076 struct FileReader
: LoadFilter
{
2077 FILE *file
; ///< The file to read from.
2078 long begin
; ///< The begin of the file.
2081 * Create the file reader, so it reads from a specific file.
2082 * @param file The file to read from.
2084 FileReader(FILE *file
) : LoadFilter(nullptr), file(file
), begin(ftell(file
))
2088 /** Make sure everything is cleaned up. */
2091 if (this->file
!= nullptr) fclose(this->file
);
2092 this->file
= nullptr;
2094 /* Make sure we don't double free. */
2098 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2100 /* We're in the process of shutting down, i.e. in "failure" mode. */
2101 if (this->file
== nullptr) return 0;
2103 return fread(buf
, 1, size
, this->file
);
2106 /* virtual */ void Reset()
2108 clearerr(this->file
);
2109 if (fseek(this->file
, this->begin
, SEEK_SET
)) {
2110 DEBUG(sl
, 1, "Could not reset the file reading");
2115 /** Yes, simply writing to a file. */
2116 struct FileWriter
: SaveFilter
{
2117 FILE *file
; ///< The file to write to.
2120 * Create the file writer, so it writes to a specific file.
2121 * @param file The file to write to.
2123 FileWriter(FILE *file
) : SaveFilter(nullptr), file(file
)
2127 /** Make sure everything is cleaned up. */
2132 /* Make sure we don't double free. */
2136 /* virtual */ void Write(byte
*buf
, size_t size
)
2138 /* We're in the process of shutting down, i.e. in "failure" mode. */
2139 if (this->file
== nullptr) return;
2141 if (fwrite(buf
, 1, size
, this->file
) != size
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE
);
2144 /* virtual */ void Finish()
2146 if (this->file
!= nullptr) fclose(this->file
);
2147 this->file
= nullptr;
2151 /*******************************************
2152 ********** START OF LZO CODE **************
2153 *******************************************/
2156 #include <lzo/lzo1x.h>
2158 /** Buffer size for the LZO compressor */
2159 static const uint LZO_BUFFER_SIZE
= 8192;
2161 /** Filter using LZO compression. */
2162 struct LZOLoadFilter
: LoadFilter
{
2164 * Initialise this filter.
2165 * @param chain The next filter in this chain.
2167 LZOLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2169 if (lzo_init() != LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2172 /* virtual */ size_t Read(byte
*buf
, size_t ssize
)
2174 assert(ssize
>= LZO_BUFFER_SIZE
);
2176 /* Buffer size is from the LZO docs plus the chunk header size. */
2177 byte out
[LZO_BUFFER_SIZE
+ LZO_BUFFER_SIZE
/ 16 + 64 + 3 + sizeof(uint32
) * 2];
2180 lzo_uint len
= ssize
;
2183 if (this->chain
->Read((byte
*)tmp
, sizeof(tmp
)) != sizeof(tmp
)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
, "File read failed");
2185 /* Check if size is bad */
2186 ((uint32
*)out
)[0] = size
= tmp
[1];
2188 if (_sl_version
!= 0) {
2189 tmp
[0] = TO_BE32(tmp
[0]);
2190 size
= TO_BE32(size
);
2193 if (size
>= sizeof(out
)) SlErrorCorrupt("Inconsistent size");
2196 if (this->chain
->Read(out
+ sizeof(uint32
), size
) != size
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2198 /* Verify checksum */
2199 if (tmp
[0] != lzo_adler32(0, out
, size
+ sizeof(uint32
))) SlErrorCorrupt("Bad checksum");
2202 int ret
= lzo1x_decompress_safe(out
+ sizeof(uint32
) * 1, size
, buf
, &len
, nullptr);
2203 if (ret
!= LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2208 /** Filter using LZO compression. */
2209 struct LZOSaveFilter
: SaveFilter
{
2211 * Initialise this filter.
2212 * @param chain The next filter in this chain.
2213 * @param compression_level The requested level of compression.
2215 LZOSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2217 if (lzo_init() != LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2220 /* virtual */ void Write(byte
*buf
, size_t size
)
2222 const lzo_bytep in
= buf
;
2223 /* Buffer size is from the LZO docs plus the chunk header size. */
2224 byte out
[LZO_BUFFER_SIZE
+ LZO_BUFFER_SIZE
/ 16 + 64 + 3 + sizeof(uint32
) * 2];
2225 byte wrkmem
[LZO1X_1_MEM_COMPRESS
];
2229 /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2230 lzo_uint len
= size
> LZO_BUFFER_SIZE
? LZO_BUFFER_SIZE
: (lzo_uint
)size
;
2231 lzo1x_1_compress(in
, len
, out
+ sizeof(uint32
) * 2, &outlen
, wrkmem
);
2232 ((uint32
*)out
)[1] = TO_BE32((uint32
)outlen
);
2233 ((uint32
*)out
)[0] = TO_BE32(lzo_adler32(0, out
+ sizeof(uint32
), outlen
+ sizeof(uint32
)));
2234 this->chain
->Write(out
, outlen
+ sizeof(uint32
) * 2);
2236 /* Move to next data chunk. */
2243 #endif /* WITH_LZO */
2245 /*********************************************
2246 ******** START OF NOCOMP CODE (uncompressed)*
2247 *********************************************/
2249 /** Filter without any compression. */
2250 struct NoCompLoadFilter
: LoadFilter
{
2252 * Initialise this filter.
2253 * @param chain The next filter in this chain.
2255 NoCompLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2259 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2261 return this->chain
->Read(buf
, size
);
2265 /** Filter without any compression. */
2266 struct NoCompSaveFilter
: SaveFilter
{
2268 * Initialise this filter.
2269 * @param chain The next filter in this chain.
2270 * @param compression_level The requested level of compression.
2272 NoCompSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2276 /* virtual */ void Write(byte
*buf
, size_t size
)
2278 this->chain
->Write(buf
, size
);
2282 /********************************************
2283 ********** START OF ZLIB CODE **************
2284 ********************************************/
2286 #if defined(WITH_ZLIB)
2289 /** Filter using Zlib compression. */
2290 struct ZlibLoadFilter
: LoadFilter
{
2291 z_stream z
; ///< Stream state we are reading from.
2292 byte fread_buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer for reading from the file.
2295 * Initialise this filter.
2296 * @param chain The next filter in this chain.
2298 ZlibLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2300 memset(&this->z
, 0, sizeof(this->z
));
2301 if (inflateInit(&this->z
) != Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2304 /** Clean everything up. */
2307 inflateEnd(&this->z
);
2310 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2312 this->z
.next_out
= buf
;
2313 this->z
.avail_out
= (uint
)size
;
2316 /* read more bytes from the file? */
2317 if (this->z
.avail_in
== 0) {
2318 this->z
.next_in
= this->fread_buf
;
2319 this->z
.avail_in
= (uint
)this->chain
->Read(this->fread_buf
, sizeof(this->fread_buf
));
2322 /* inflate the data */
2323 int r
= inflate(&this->z
, 0);
2324 if (r
== Z_STREAM_END
) break;
2326 if (r
!= Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "inflate() failed");
2327 } while (this->z
.avail_out
!= 0);
2329 return size
- this->z
.avail_out
;
2333 /** Filter using Zlib compression. */
2334 struct ZlibSaveFilter
: SaveFilter
{
2335 z_stream z
; ///< Stream state we are writing to.
2338 * Initialise this filter.
2339 * @param chain The next filter in this chain.
2340 * @param compression_level The requested level of compression.
2342 ZlibSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2344 memset(&this->z
, 0, sizeof(this->z
));
2345 if (deflateInit(&this->z
, compression_level
) != Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2348 /** Clean up what we allocated. */
2351 deflateEnd(&this->z
);
2355 * Helper loop for writing the data.
2356 * @param p The bytes to write.
2357 * @param len Amount of bytes to write.
2358 * @param mode Mode for deflate.
2360 void WriteLoop(byte
*p
, size_t len
, int mode
)
2362 byte buf
[MEMORY_CHUNK_SIZE
]; // output buffer
2364 this->z
.next_in
= p
;
2365 this->z
.avail_in
= (uInt
)len
;
2367 this->z
.next_out
= buf
;
2368 this->z
.avail_out
= sizeof(buf
);
2371 * For the poor next soul who sees many valgrind warnings of the
2372 * "Conditional jump or move depends on uninitialised value(s)" kind:
2373 * According to the author of zlib it is not a bug and it won't be fixed.
2374 * http://groups.google.com/group/comp.compression/browse_thread/thread/b154b8def8c2a3ef/cdf9b8729ce17ee2
2375 * [Mark Adler, Feb 24 2004, 'zlib-1.2.1 valgrind warnings' in the newsgroup comp.compression]
2377 int r
= deflate(&this->z
, mode
);
2379 /* bytes were emitted? */
2380 if ((n
= sizeof(buf
) - this->z
.avail_out
) != 0) {
2381 this->chain
->Write(buf
, n
);
2383 if (r
== Z_STREAM_END
) break;
2385 if (r
!= Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "zlib returned error code");
2386 } while (this->z
.avail_in
|| !this->z
.avail_out
);
2389 /* virtual */ void Write(byte
*buf
, size_t size
)
2391 this->WriteLoop(buf
, size
, 0);
2394 /* virtual */ void Finish()
2396 this->WriteLoop(nullptr, 0, Z_FINISH
);
2397 this->chain
->Finish();
2401 #endif /* WITH_ZLIB */
2403 /********************************************
2404 ********** START OF LZMA CODE **************
2405 ********************************************/
2407 #if defined(WITH_LZMA)
2411 * Have a copy of an initialised LZMA stream. We need this as it's
2412 * impossible to "re"-assign LZMA_STREAM_INIT to a variable in some
2413 * compilers, i.e. LZMA_STREAM_INIT can't be used to set something.
2414 * This var has to be used instead.
2416 static const lzma_stream _lzma_init
= LZMA_STREAM_INIT
;
2418 /** Filter without any compression. */
2419 struct LZMALoadFilter
: LoadFilter
{
2420 lzma_stream lzma
; ///< Stream state that we are reading from.
2421 byte fread_buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer for reading from the file.
2424 * Initialise this filter.
2425 * @param chain The next filter in this chain.
2427 LZMALoadFilter(LoadFilter
*chain
) : LoadFilter(chain
), lzma(_lzma_init
)
2429 /* Allow saves up to 256 MB uncompressed */
2430 if (lzma_auto_decoder(&this->lzma
, 1 << 28, 0) != LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2433 /** Clean everything up. */
2436 lzma_end(&this->lzma
);
2439 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2441 this->lzma
.next_out
= buf
;
2442 this->lzma
.avail_out
= size
;
2445 /* read more bytes from the file? */
2446 if (this->lzma
.avail_in
== 0) {
2447 this->lzma
.next_in
= this->fread_buf
;
2448 this->lzma
.avail_in
= this->chain
->Read(this->fread_buf
, sizeof(this->fread_buf
));
2451 /* inflate the data */
2452 lzma_ret r
= lzma_code(&this->lzma
, LZMA_RUN
);
2453 if (r
== LZMA_STREAM_END
) break;
2454 if (r
!= LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "liblzma returned error code");
2455 } while (this->lzma
.avail_out
!= 0);
2457 return size
- this->lzma
.avail_out
;
2461 /** Filter using LZMA compression. */
2462 struct LZMASaveFilter
: SaveFilter
{
2463 lzma_stream lzma
; ///< Stream state that we are writing to.
2466 * Initialise this filter.
2467 * @param chain The next filter in this chain.
2468 * @param compression_level The requested level of compression.
2470 LZMASaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
), lzma(_lzma_init
)
2472 if (lzma_easy_encoder(&this->lzma
, compression_level
, LZMA_CHECK_CRC32
) != LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2475 /** Clean up what we allocated. */
2478 lzma_end(&this->lzma
);
2482 * Helper loop for writing the data.
2483 * @param p The bytes to write.
2484 * @param len Amount of bytes to write.
2485 * @param action Action for lzma_code.
2487 void WriteLoop(byte
*p
, size_t len
, lzma_action action
)
2489 byte buf
[MEMORY_CHUNK_SIZE
]; // output buffer
2491 this->lzma
.next_in
= p
;
2492 this->lzma
.avail_in
= len
;
2494 this->lzma
.next_out
= buf
;
2495 this->lzma
.avail_out
= sizeof(buf
);
2497 lzma_ret r
= lzma_code(&this->lzma
, action
);
2499 /* bytes were emitted? */
2500 if ((n
= sizeof(buf
) - this->lzma
.avail_out
) != 0) {
2501 this->chain
->Write(buf
, n
);
2503 if (r
== LZMA_STREAM_END
) break;
2504 if (r
!= LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "liblzma returned error code");
2505 } while (this->lzma
.avail_in
|| !this->lzma
.avail_out
);
2508 /* virtual */ void Write(byte
*buf
, size_t size
)
2510 this->WriteLoop(buf
, size
, LZMA_RUN
);
2513 /* virtual */ void Finish()
2515 this->WriteLoop(nullptr, 0, LZMA_FINISH
);
2516 this->chain
->Finish();
2520 #endif /* WITH_LZMA */
2522 /*******************************************
2523 ************* END OF CODE *****************
2524 *******************************************/
2526 /** The format for a reader/writer type of a savegame */
2527 struct SaveLoadFormat
{
2528 const char *name
; ///< name of the compressor/decompressor (debug-only)
2529 uint32 tag
; ///< the 4-letter tag by which it is identified in the savegame
2531 LoadFilter
*(*init_load
)(LoadFilter
*chain
); ///< Constructor for the load filter.
2532 SaveFilter
*(*init_write
)(SaveFilter
*chain
, byte compression
); ///< Constructor for the save filter.
2534 byte min_compression
; ///< the minimum compression level of this format
2535 byte default_compression
; ///< the default compression level of this format
2536 byte max_compression
; ///< the maximum compression level of this format
2539 /** The different saveload formats known/understood by OpenTTD. */
2540 static const SaveLoadFormat _saveload_formats
[] = {
2541 #if defined(WITH_LZO)
2542 /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2543 {"lzo", TO_BE32X('OTTD'), CreateLoadFilter
<LZOLoadFilter
>, CreateSaveFilter
<LZOSaveFilter
>, 0, 0, 0},
2545 {"lzo", TO_BE32X('OTTD'), nullptr, nullptr, 0, 0, 0},
2547 /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2548 {"none", TO_BE32X('OTTN'), CreateLoadFilter
<NoCompLoadFilter
>, CreateSaveFilter
<NoCompSaveFilter
>, 0, 0, 0},
2549 #if defined(WITH_ZLIB)
2550 /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2551 * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2552 * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2553 {"zlib", TO_BE32X('OTTZ'), CreateLoadFilter
<ZlibLoadFilter
>, CreateSaveFilter
<ZlibSaveFilter
>, 0, 6, 9},
2555 {"zlib", TO_BE32X('OTTZ'), nullptr, nullptr, 0, 0, 0},
2557 #if defined(WITH_LZMA)
2558 /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2559 * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2560 * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2561 * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2562 * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2563 {"lzma", TO_BE32X('OTTX'), CreateLoadFilter
<LZMALoadFilter
>, CreateSaveFilter
<LZMASaveFilter
>, 0, 2, 9},
2565 {"lzma", TO_BE32X('OTTX'), nullptr, nullptr, 0, 0, 0},
2570 * Return the savegameformat of the game. Whether it was created with ZLIB compression
2571 * uncompressed, or another type
2572 * @param s Name of the savegame format. If nullptr it picks the first available one
2573 * @param compression_level Output for telling what compression level we want.
2574 * @return Pointer to SaveLoadFormat struct giving all characteristics of this type of savegame
2576 static const SaveLoadFormat
*GetSavegameFormat(char *s
, byte
*compression_level
)
2578 const SaveLoadFormat
*def
= lastof(_saveload_formats
);
2580 /* find default savegame format, the highest one with which files can be written */
2581 while (!def
->init_write
) def
--;
2584 /* Get the ":..." of the compression level out of the way */
2585 char *complevel
= strrchr(s
, ':');
2586 if (complevel
!= nullptr) *complevel
= '\0';
2588 for (const SaveLoadFormat
*slf
= &_saveload_formats
[0]; slf
!= endof(_saveload_formats
); slf
++) {
2589 if (slf
->init_write
!= nullptr && strcmp(s
, slf
->name
) == 0) {
2590 *compression_level
= slf
->default_compression
;
2591 if (complevel
!= nullptr) {
2592 /* There is a compression level in the string.
2593 * First restore the : we removed to do proper name matching,
2594 * then move the the begin of the actual version. */
2598 /* Get the version and determine whether all went fine. */
2600 long level
= strtol(complevel
, &end
, 10);
2601 if (end
== complevel
|| level
!= Clamp(level
, slf
->min_compression
, slf
->max_compression
)) {
2602 SetDParamStr(0, complevel
);
2603 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL
, WL_CRITICAL
);
2605 *compression_level
= level
;
2613 SetDParamStr(1, def
->name
);
2614 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM
, WL_CRITICAL
);
2616 /* Restore the string by adding the : back */
2617 if (complevel
!= nullptr) *complevel
= ':';
2619 *compression_level
= def
->default_compression
;
2623 /* actual loader/saver function */
2624 void InitializeGame(uint size_x
, uint size_y
, bool reset_date
, bool reset_settings
);
2625 extern bool AfterLoadGame();
2626 extern bool LoadOldSaveGame(const char *file
);
2629 * Clear/free saveload state.
2631 static inline void ClearSaveLoadState()
2634 _sl
.dumper
= nullptr;
2640 _sl
.reader
= nullptr;
2647 * Update the gui accordingly when starting saving
2648 * and set locks on saveload. Also turn off fast-forward cause with that
2649 * saving takes Aaaaages
2651 static void SaveFileStart()
2653 _sl
.ff_state
= _fast_forward
;
2655 SetMouseCursorBusy(true);
2657 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_SAVELOAD_START
);
2658 _sl
.saveinprogress
= true;
2661 /** Update the gui accordingly when saving is done and release locks on saveload. */
2662 static void SaveFileDone()
2664 if (_game_mode
!= GM_MENU
) _fast_forward
= _sl
.ff_state
;
2665 SetMouseCursorBusy(false);
2667 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_SAVELOAD_FINISH
);
2668 _sl
.saveinprogress
= false;
2671 /** Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friends) */
2672 void SetSaveLoadError(StringID str
)
2674 _sl
.error_str
= str
;
2677 /** Get the string representation of the error message */
2678 const char *GetSaveLoadErrorString()
2680 SetDParam(0, _sl
.error_str
);
2681 SetDParamStr(1, _sl
.extra_msg
);
2683 static char err_str
[512];
2684 GetString(err_str
, _sl
.action
== SLA_SAVE
? STR_ERROR_GAME_SAVE_FAILED
: STR_ERROR_GAME_LOAD_FAILED
, lastof(err_str
));
2688 /** Show a gui message when saving has failed */
2689 static void SaveFileError()
2691 SetDParamStr(0, GetSaveLoadErrorString());
2692 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
2697 * We have written the whole game into memory, _memory_savegame, now find
2698 * and appropriate compressor and start writing to file.
2700 static SaveOrLoadResult
SaveFileToDisk(bool threaded
)
2704 const SaveLoadFormat
*fmt
= GetSavegameFormat(_savegame_format
, &compression
);
2706 /* We have written our stuff to memory, now write it to file! */
2707 uint32 hdr
[2] = { fmt
->tag
, TO_BE32(SAVEGAME_VERSION
<< 16) };
2708 _sl
.sf
->Write((byte
*)hdr
, sizeof(hdr
));
2710 _sl
.sf
= fmt
->init_write(_sl
.sf
, compression
);
2711 _sl
.dumper
->Flush(_sl
.sf
);
2713 ClearSaveLoadState();
2715 if (threaded
) SetAsyncSaveFinish(SaveFileDone
);
2719 ClearSaveLoadState();
2721 AsyncSaveFinishProc asfp
= SaveFileDone
;
2723 /* We don't want to shout when saving is just
2724 * cancelled due to a client disconnecting. */
2725 if (_sl
.error_str
!= STR_NETWORK_ERROR_LOSTCONNECTION
) {
2726 /* Skip the "colour" character */
2727 DEBUG(sl
, 0, "%s", GetSaveLoadErrorString() + 3);
2728 asfp
= SaveFileError
;
2732 SetAsyncSaveFinish(asfp
);
2740 /** Thread run function for saving the file to disk. */
2741 static void SaveFileToDiskThread(void *arg
)
2743 SaveFileToDisk(true);
2746 void WaitTillSaved()
2748 if (_save_thread
== nullptr) return;
2750 _save_thread
->Join();
2751 delete _save_thread
;
2752 _save_thread
= nullptr;
2754 /* Make sure every other state is handled properly as well. */
2755 ProcessAsyncSaveFinish();
2759 * Actually perform the saving of the savegame.
2760 * General tactics is to first save the game to memory, then write it to file
2761 * using the writer, either in threaded mode if possible, or single-threaded.
2762 * @param writer The filter to write the savegame to.
2763 * @param threaded Whether to try to perform the saving asynchronously.
2764 * @return Return the result of the action. #SL_OK or #SL_ERROR
2766 static SaveOrLoadResult
DoSave(SaveFilter
*writer
, bool threaded
)
2768 assert(!_sl
.saveinprogress
);
2770 _sl
.dumper
= new MemoryDumper();
2773 _sl_version
= SAVEGAME_VERSION
;
2775 SaveViewportBeforeSaveGame();
2779 if (!threaded
|| !ThreadObject::New(&SaveFileToDiskThread
, nullptr, &_save_thread
, "ottd:savegame")) {
2780 if (threaded
) DEBUG(sl
, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
2782 SaveOrLoadResult result
= SaveFileToDisk(false);
2792 * Save the game using a (writer) filter.
2793 * @param writer The filter to write the savegame to.
2794 * @param threaded Whether to try to perform the saving asynchronously.
2795 * @return Return the result of the action. #SL_OK or #SL_ERROR
2797 SaveOrLoadResult
SaveWithFilter(SaveFilter
*writer
, bool threaded
)
2800 _sl
.action
= SLA_SAVE
;
2801 return DoSave(writer
, threaded
);
2803 ClearSaveLoadState();
2809 * Actually perform the loading of a "non-old" savegame.
2810 * @param reader The filter to read the savegame from.
2811 * @param load_check Whether to perform the checking ("preview") or actually load the game.
2812 * @return Return the result of the action. #SL_OK or #SL_REINIT ("unload" the game)
2814 static SaveOrLoadResult
DoLoad(LoadFilter
*reader
, bool load_check
)
2819 /* Clear previous check data */
2820 _load_check_data
.Clear();
2821 /* Mark SL_LOAD_CHECK as supported for this savegame. */
2822 _load_check_data
.checkable
= true;
2826 if (_sl
.lf
->Read((byte
*)hdr
, sizeof(hdr
)) != sizeof(hdr
)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2828 /* see if we have any loader for this type. */
2829 const SaveLoadFormat
*fmt
= _saveload_formats
;
2831 /* No loader found, treat as version 0 and use LZO format */
2832 if (fmt
== endof(_saveload_formats
)) {
2833 DEBUG(sl
, 0, "Unknown savegame type, trying to load it as the buggy format");
2836 _sl_minor_version
= 0;
2838 /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
2839 fmt
= _saveload_formats
;
2841 if (fmt
== endof(_saveload_formats
)) {
2842 /* Who removed LZO support? Bad bad boy! */
2845 if (fmt
->tag
== TO_BE32X('OTTD')) break;
2851 if (fmt
->tag
== hdr
[0]) {
2852 /* check version number */
2853 _sl_version
= TO_BE32(hdr
[1]) >> 16;
2854 /* Minor is not used anymore from version 18.0, but it is still needed
2855 * in versions before that (4 cases) which can't be removed easy.
2856 * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
2857 _sl_minor_version
= (TO_BE32(hdr
[1]) >> 8) & 0xFF;
2859 DEBUG(sl
, 1, "Loading savegame version %d", _sl_version
);
2861 /* Is the version higher than the current? */
2862 if (_sl_version
> SAVEGAME_VERSION
) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME
);
2869 /* loader for this savegame type is not implemented? */
2870 if (fmt
->init_load
== nullptr) {
2872 seprintf(err_str
, lastof(err_str
), "Loader for '%s' is not available.", fmt
->name
);
2873 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, err_str
);
2876 _sl
.lf
= fmt
->init_load(_sl
.lf
);
2877 _sl
.reader
= new ReadBuffer(_sl
.lf
);
2881 /* Old maps were hardcoded to 256x256 and thus did not contain
2882 * any mapsize information. Pre-initialize to 256x256 to not to
2883 * confuse old games */
2884 InitializeGame(256, 256, true, true);
2888 if (IsSavegameVersionBefore(4)) {
2890 * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
2891 * shared savegame version 4. Anything before that 'obviously'
2892 * does not have any NewGRFs. Between the introduction and
2893 * savegame version 41 (just before 0.5) the NewGRF settings
2894 * were not stored in the savegame and they were loaded by
2895 * using the settings from the main menu.
2897 * - savegame version < 4: do not load any NewGRFs.
2898 * - savegame version >= 41: load NewGRFs from savegame, which is
2899 * already done at this stage by
2900 * overwriting the main menu settings.
2901 * - other savegame versions: use main menu settings.
2903 * This means that users *can* crash savegame version 4..40
2904 * savegames if they set incompatible NewGRFs in the main menu,
2905 * but can't crash anymore for savegame version < 4 savegames.
2907 * Note: this is done here because AfterLoadGame is also called
2908 * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
2910 ClearGRFConfigList(&_grfconfig
);
2915 /* Load chunks into _load_check_data.
2916 * No pools are loaded. References are not possible, and thus do not need resolving. */
2917 SlLoadCheckChunks();
2919 /* Load chunks and resolve references */
2924 ClearSaveLoadState();
2926 _savegame_type
= SGT_OTTD
;
2929 /* The only part from AfterLoadGame() we need */
2930 _load_check_data
.grf_compatibility
= IsGoodGRFConfigList(_load_check_data
.grfconfig
);
2932 GamelogStartAction(GLAT_LOAD
);
2934 /* After loading fix up savegame for any internal changes that
2935 * might have occurred since then. If it fails, load back the old game. */
2936 if (!AfterLoadGame()) {
2937 GamelogStopAction();
2941 GamelogStopAction();
2948 * Load the game using a (reader) filter.
2949 * @param reader The filter to read the savegame from.
2950 * @return Return the result of the action. #SL_OK or #SL_REINIT ("unload" the game)
2952 SaveOrLoadResult
LoadWithFilter(LoadFilter
*reader
)
2955 _sl
.action
= SLA_LOAD
;
2956 return DoLoad(reader
, false);
2958 ClearSaveLoadState();
2964 * Main Save or Load function where the high-level saveload functions are
2965 * handled. It opens the savegame, selects format and checks versions
2966 * @param filename The name of the savegame being created/loaded
2967 * @param mode Save or load mode. Load can also be a TTD(Patch) game. Use #SL_LOAD, #SL_OLD_LOAD, #SL_LOAD_CHECK, or #SL_SAVE.
2968 * @param sb The sub directory to save the savegame in
2969 * @param threaded True when threaded saving is allowed
2970 * @return Return the result of the action. #SL_OK, #SL_ERROR, or #SL_REINIT ("unload" the game)
2972 SaveOrLoadResult
SaveOrLoad(const char *filename
, SaveLoadOperation fop
, DetailedFileType dft
, Subdirectory sb
, bool threaded
)
2974 /* An instance of saving is already active, so don't go saving again */
2975 if (_sl
.saveinprogress
&& fop
== SLO_SAVE
&& dft
== DFT_GAME_FILE
&& threaded
) {
2976 /* if not an autosave, but a user action, show error message */
2977 if (!_do_autosave
) ShowErrorMessage(STR_ERROR_SAVE_STILL_IN_PROGRESS
, INVALID_STRING_ID
, WL_ERROR
);
2983 /* Load a TTDLX or TTDPatch game */
2984 if (fop
== SLO_LOAD
&& dft
== DFT_OLD_GAME_FILE
) {
2985 InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
2987 /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
2988 * and if so a new NewGRF list will be made in LoadOldSaveGame.
2989 * Note: this is done here because AfterLoadGame is also called
2990 * for OTTD savegames which have their own NewGRF logic. */
2991 ClearGRFConfigList(&_grfconfig
);
2993 if (!LoadOldSaveGame(filename
)) return SL_REINIT
;
2995 _sl_minor_version
= 0;
2996 GamelogStartAction(GLAT_LOAD
);
2997 if (!AfterLoadGame()) {
2998 GamelogStopAction();
3001 GamelogStopAction();
3005 assert(dft
== DFT_GAME_FILE
);
3008 _sl
.action
= SLA_LOAD_CHECK
;
3012 _sl
.action
= SLA_LOAD
;
3016 _sl
.action
= SLA_SAVE
;
3019 default: NOT_REACHED();
3022 FILE *fh
= (fop
== SLO_SAVE
) ? FioFOpenFile(filename
, "wb", sb
) : FioFOpenFile(filename
, "rb", sb
);
3024 /* Make it a little easier to load savegames from the console */
3025 if (fh
== nullptr && fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", SAVE_DIR
);
3026 if (fh
== nullptr && fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", BASE_DIR
);
3027 if (fh
== nullptr && fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", SCENARIO_DIR
);
3029 if (fh
== nullptr) {
3030 SlError(fop
== SLO_SAVE
? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE
: STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
3033 if (fop
== SLO_SAVE
) { // SAVE game
3034 DEBUG(desync
, 1, "save: %08x; %02x; %s", _date
, _date_fract
, filename
);
3035 if (_network_server
|| !_settings_client
.gui
.threaded_saves
) threaded
= false;
3037 return DoSave(new FileWriter(fh
), threaded
);
3041 assert(fop
== SLO_LOAD
|| fop
== SLO_CHECK
);
3042 DEBUG(desync
, 1, "load: %s", filename
);
3043 return DoLoad(new FileReader(fh
), fop
== SLO_CHECK
);
3045 /* This code may be executed both for old and new save games. */
3046 ClearSaveLoadState();
3048 /* Skip the "colour" character */
3049 if (fop
!= SLO_CHECK
) DEBUG(sl
, 0, "%s", GetSaveLoadErrorString() + 3);
3051 /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3052 return (fop
== SLO_LOAD
) ? SL_REINIT
: SL_ERROR
;
3056 /** Do a save when exiting the game (_settings_client.gui.autosave_on_exit) */
3059 SaveOrLoad("exit.sav", SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
);
3063 * Fill the buffer with the default name for a savegame *or* screenshot.
3064 * @param buf the buffer to write to.
3065 * @param last the last element in the buffer.
3067 void GenerateDefaultSaveName(char *buf
, const char *last
)
3069 /* Check if we have a name for this map, which is the name of the first
3070 * available company. When there's no company available we'll use
3071 * 'Spectator' as "company" name. */
3072 CompanyID cid
= _local_company
;
3073 if (!Company::IsValidID(cid
)) {
3075 FOR_ALL_COMPANIES(c
) {
3083 /* Insert current date */
3084 switch (_settings_client
.gui
.date_format_in_default_names
) {
3085 case 0: SetDParam(1, STR_JUST_DATE_LONG
); break;
3086 case 1: SetDParam(1, STR_JUST_DATE
); break;
3087 case 2: SetDParam(1, STR_JUST_DATE_ISO
); break;
3088 default: NOT_REACHED();
3090 SetDParam(2, _date
);
3092 /* Get the correct string (special string for when there's not company) */
3093 GetString(buf
, !Company::IsValidID(cid
) ? STR_SAVEGAME_NAME_SPECTATOR
: STR_SAVEGAME_NAME_DEFAULT
, last
);
3094 SanitizeFilename(buf
);
3098 * Set the mode and file type of the file to save or load based on the type of file entry at the file system.
3099 * @param ft Type of file entry of the file system.
3101 void FileToSaveLoad::SetMode(FiosType ft
)
3103 this->SetMode(SLO_LOAD
, GetAbstractFileType(ft
), GetDetailedFileType(ft
));
3107 * Set the mode and file type of the file to save or load.
3108 * @param fop File operation being performed.
3109 * @param aft Abstract file type.
3110 * @param dft Detailed file type.
3112 void FileToSaveLoad::SetMode(SaveLoadOperation fop
, AbstractFileType aft
, DetailedFileType dft
)
3114 if (aft
== FT_INVALID
|| aft
== FT_NONE
) {
3115 this->file_op
= SLO_INVALID
;
3116 this->detail_ftype
= DFT_INVALID
;
3117 this->abstract_ftype
= FT_INVALID
;
3121 this->file_op
= fop
;
3122 this->detail_ftype
= dft
;
3123 this->abstract_ftype
= aft
;
3127 * Set the name of the file.
3128 * @param name Name of the file.
3130 void FileToSaveLoad::SetName(const char *name
)
3132 strecpy(this->name
, name
, lastof(this->name
));
3136 * Set the title of the file.
3137 * @param title Title of the file.
3139 void FileToSaveLoad::SetTitle(const char *title
)
3141 strecpy(this->title
, title
, lastof(this->title
));
3146 * Function to get the type of the savegame by looking at the file header.
3147 * NOTICE: Not used right now, but could be used if extensions of savegames are garbled
3148 * @param file Savegame to be checked
3149 * @return SL_OLD_LOAD or SL_LOAD of the file
3151 int GetSavegameType(char *file
)
3153 const SaveLoadFormat
*fmt
;
3156 int mode
= SL_OLD_LOAD
;
3158 f
= fopen(file
, "rb");
3159 if (fread(&hdr
, sizeof(hdr
), 1, f
) != 1) {
3160 DEBUG(sl
, 0, "Savegame is obsolete or invalid format");
3161 mode
= SL_LOAD
; // don't try to get filename, just show name as it is written
3163 /* see if we have any loader for this type. */
3164 for (fmt
= _saveload_formats
; fmt
!= endof(_saveload_formats
); fmt
++) {
3165 if (fmt
->tag
== hdr
) {
3166 mode
= SL_LOAD
; // new type of savegame