OpenTTD Source 20261129-master-g72a8bdc861
saveload.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
22
23#include "../stdafx.h"
24#include "../debug.h"
25#include "../station_base.h"
26#include "../thread.h"
27#include "../town.h"
28#include "../network/network.h"
29#include "../window_func.h"
30#include "../strings_func.h"
34#include "../vehicle_base.h"
35#include "../company_func.h"
37#include "../roadstop_base.h"
40#include "../statusbar_gui.h"
41#include "../fileio_func.h"
42#include "../gamelog.h"
43#include "../string_func.h"
44#include "../fios.h"
45#include "../error.h"
46#include "../strings_type.h"
47#include "../newgrf_railtype.h"
48#include "../newgrf_roadtype.h"
50#include "saveload_error.hpp"
51#include "saveload_filter.h"
52#include "saveload_func.h"
53#include "saveload_internal.h"
54
55#include <atomic>
56#ifdef __EMSCRIPTEN__
57# include <emscripten.h>
58#endif
59
60#ifdef WITH_LZO
61#include <lzo/lzo1x.h>
62#endif
63
64#if defined(WITH_ZLIB)
65#include <zlib.h>
66#endif /* WITH_ZLIB */
67
68#if defined(WITH_LIBLZMA)
69#include <lzma.h>
70#endif /* WITH_LIBLZMA */
71
73#include "table/strings.h"
74
75#include "../safeguards.h"
76
78
81
82uint32_t _ttdp_version;
85std::string _savegame_format;
87
89enum class SaveLoadAction : uint8_t {
95};
96
97enum class NeedLength : uint8_t {
101};
102
104static const size_t MEMORY_CHUNK_SIZE = 128 * 1024;
105
109 uint8_t *bufp = nullptr;
110 uint8_t *bufe = nullptr;
111 std::shared_ptr<LoadFilter> reader{};
112 size_t read = 0;
113
118 ReadBuffer(std::shared_ptr<LoadFilter> reader) : reader(std::move(reader))
119 {
120 }
121
122 inline uint8_t ReadByte()
123 {
124 if (this->bufp == this->bufe) {
125 size_t len = this->reader->Read(this->buf, lengthof(this->buf));
126 if (len == 0) SlErrorCorrupt("Unexpected end of chunk");
127
128 this->read += len;
129 this->bufp = this->buf;
130 this->bufe = this->buf + len;
131 }
132
133 return *this->bufp++;
134 }
135
140 size_t GetSize() const
141 {
142 return this->read - (this->bufe - this->bufp);
143 }
144};
145
146
149 std::vector<std::unique_ptr<uint8_t[]>> blocks{};
150 uint8_t *buf = nullptr;
151 uint8_t *bufe = nullptr;
152
157 inline void WriteByte(uint8_t b)
158 {
159 /* Are we at the end of this chunk? */
160 if (this->buf == this->bufe) {
161 this->buf = this->blocks.emplace_back(std::make_unique<uint8_t[]>(MEMORY_CHUNK_SIZE)).get();
162 this->bufe = this->buf + MEMORY_CHUNK_SIZE;
163 }
164
165 *this->buf++ = b;
166 }
167
172 void Flush(std::shared_ptr<SaveFilter> writer)
173 {
174 uint i = 0;
175 size_t t = this->GetSize();
176
177 while (t > 0) {
178 size_t to_write = std::min(MEMORY_CHUNK_SIZE, t);
179
180 writer->Write(this->blocks[i++].get(), to_write);
181 t -= to_write;
182 }
183
184 writer->Finish();
185 }
186
191 size_t GetSize() const
192 {
193 return this->blocks.size() * MEMORY_CHUNK_SIZE - (this->bufe - this->buf);
194 }
195};
196
202 bool error;
203
204 size_t obj_len;
205 int array_index, last_array_index;
207
208 std::unique_ptr<MemoryDumper> dumper;
209 std::shared_ptr<SaveFilter> sf;
210
211 std::unique_ptr<ReadBuffer> reader;
212 std::shared_ptr<LoadFilter> lf;
213
215 std::string extra_msg;
216
218};
219
221
222static const std::vector<ChunkHandlerRef> &ChunkHandlers()
223{
224 /* These define the chunks */
225 extern const ChunkHandlerTable _gamelog_chunk_handlers;
226 extern const ChunkHandlerTable _map_chunk_handlers;
227 extern const ChunkHandlerTable _misc_chunk_handlers;
228 extern const ChunkHandlerTable _name_chunk_handlers;
229 extern const ChunkHandlerTable _cheat_chunk_handlers;
230 extern const ChunkHandlerTable _setting_chunk_handlers;
231 extern const ChunkHandlerTable _company_chunk_handlers;
232 extern const ChunkHandlerTable _engine_chunk_handlers;
233 extern const ChunkHandlerTable _veh_chunk_handlers;
234 extern const ChunkHandlerTable _waypoint_chunk_handlers;
235 extern const ChunkHandlerTable _depot_chunk_handlers;
236 extern const ChunkHandlerTable _order_chunk_handlers;
237 extern const ChunkHandlerTable _town_chunk_handlers;
238 extern const ChunkHandlerTable _sign_chunk_handlers;
239 extern const ChunkHandlerTable _station_chunk_handlers;
240 extern const ChunkHandlerTable _industry_chunk_handlers;
241 extern const ChunkHandlerTable _economy_chunk_handlers;
242 extern const ChunkHandlerTable _subsidy_chunk_handlers;
243 extern const ChunkHandlerTable _cargomonitor_chunk_handlers;
244 extern const ChunkHandlerTable _goal_chunk_handlers;
245 extern const ChunkHandlerTable _story_page_chunk_handlers;
246 extern const ChunkHandlerTable _league_chunk_handlers;
247 extern const ChunkHandlerTable _ai_chunk_handlers;
248 extern const ChunkHandlerTable _game_chunk_handlers;
249 extern const ChunkHandlerTable _animated_tile_chunk_handlers;
250 extern const ChunkHandlerTable _newgrf_chunk_handlers;
251 extern const ChunkHandlerTable _group_chunk_handlers;
252 extern const ChunkHandlerTable _cargopacket_chunk_handlers;
253 extern const ChunkHandlerTable _autoreplace_chunk_handlers;
254 extern const ChunkHandlerTable _labelmaps_chunk_handlers;
255 extern const ChunkHandlerTable _linkgraph_chunk_handlers;
256 extern const ChunkHandlerTable _airport_chunk_handlers;
257 extern const ChunkHandlerTable _object_chunk_handlers;
258 extern const ChunkHandlerTable _persistent_storage_chunk_handlers;
259 extern const ChunkHandlerTable _water_region_chunk_handlers;
260 extern const ChunkHandlerTable _randomizer_chunk_handlers;
261
263 static const ChunkHandlerTable _chunk_handler_tables[] = {
264 _gamelog_chunk_handlers,
265 _map_chunk_handlers,
266 _misc_chunk_handlers,
267 _name_chunk_handlers,
268 _cheat_chunk_handlers,
269 _setting_chunk_handlers,
270 _veh_chunk_handlers,
271 _waypoint_chunk_handlers,
272 _depot_chunk_handlers,
273 _order_chunk_handlers,
274 _industry_chunk_handlers,
275 _economy_chunk_handlers,
276 _subsidy_chunk_handlers,
277 _cargomonitor_chunk_handlers,
278 _goal_chunk_handlers,
279 _story_page_chunk_handlers,
280 _league_chunk_handlers,
281 _engine_chunk_handlers,
282 _town_chunk_handlers,
283 _sign_chunk_handlers,
284 _station_chunk_handlers,
285 _company_chunk_handlers,
286 _ai_chunk_handlers,
287 _game_chunk_handlers,
288 _animated_tile_chunk_handlers,
289 _newgrf_chunk_handlers,
290 _group_chunk_handlers,
291 _cargopacket_chunk_handlers,
292 _autoreplace_chunk_handlers,
293 _labelmaps_chunk_handlers,
294 _linkgraph_chunk_handlers,
295 _airport_chunk_handlers,
296 _object_chunk_handlers,
297 _persistent_storage_chunk_handlers,
298 _water_region_chunk_handlers,
299 _randomizer_chunk_handlers,
300 };
301
302 static std::vector<ChunkHandlerRef> _chunk_handlers;
303
304 if (_chunk_handlers.empty()) {
305 for (auto &chunk_handler_table : _chunk_handler_tables) {
306 for (auto &chunk_handler : chunk_handler_table) {
307 _chunk_handlers.push_back(chunk_handler);
308 }
309 }
310 }
311
312 return _chunk_handlers;
313}
314
316static void SlNullPointers()
317{
318 _sl.action = SaveLoadAction::Null;
319
320 /* We don't want any savegame conversion code to run
321 * during NULLing; especially those that try to get
322 * pointers from other pools. */
324
325 for (const ChunkHandler &ch : ChunkHandlers()) {
326 Debug(Facility::Sl, Severity::Notice, "Nulling pointers for {}", ch.GetName());
327 ch.FixPointers();
328 }
329
330 assert(_sl.action == SaveLoadAction::Null);
331}
332
341[[noreturn]] void SlError(StringID string, const std::string &extra_msg)
342{
343 /* Distinguish between loading into _load_check_data vs. normal save/load. */
344 if (_sl.action == SaveLoadAction::LoadCheck) {
345 _load_check_data.error = string;
346 _load_check_data.error_msg = extra_msg;
347 } else {
348 _sl.error_str = string;
349 _sl.extra_msg = extra_msg;
350 }
351
352 /* We have to nullptr all pointers here; we might be in a state where
353 * the pointers are actually filled with indices, which means that
354 * when we access them during cleaning the pool dereferences of
355 * those indices will be made with segmentation faults as result. */
356 if (_sl.action == SaveLoadAction::Load || _sl.action == SaveLoadAction::Ptrs) SlNullPointers();
357
358 /* Logging could be active. */
359 _gamelog.StopAnyAction();
360
361 throw std::exception();
362}
363
371[[noreturn]] void SlErrorCorrupt(const std::string &msg)
372{
373 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, msg);
374}
375
376
377typedef void (*AsyncSaveFinishProc)();
378static std::atomic<AsyncSaveFinishProc> _async_save_finish;
379static std::thread _save_thread;
380
386{
387 if (_exit_game) return;
388 while (_async_save_finish.load(std::memory_order_acquire) != nullptr) CSleep(10);
389
390 _async_save_finish.store(proc, std::memory_order_release);
391}
392
397{
398 AsyncSaveFinishProc proc = _async_save_finish.exchange(nullptr, std::memory_order_acq_rel);
399 if (proc == nullptr) return;
400
401 proc();
402
403 if (_save_thread.joinable()) {
404 _save_thread.join();
405 }
406}
407
412uint8_t SlReadByte()
413{
414 return _sl.reader->ReadByte();
415}
416
421void SlWriteByte(uint8_t b)
422{
423 _sl.dumper->WriteByte(b);
424}
425
426static inline int SlReadUint16()
427{
428 int x = SlReadByte() << 8;
429 return x | SlReadByte();
430}
431
432static inline uint32_t SlReadUint32()
433{
434 uint32_t x = SlReadUint16() << 16;
435 return x | SlReadUint16();
436}
437
438static inline uint64_t SlReadUint64()
439{
440 uint32_t x = SlReadUint32();
441 uint32_t y = SlReadUint32();
442 return static_cast<uint64_t>(x) << 32 | y;
443}
444
445static inline void SlWriteUint16(uint16_t v)
446{
447 SlWriteByte(GB(v, 8, 8));
448 SlWriteByte(GB(v, 0, 8));
449}
450
451static inline void SlWriteUint32(uint32_t v)
452{
453 SlWriteUint16(GB(v, 16, 16));
454 SlWriteUint16(GB(v, 0, 16));
455}
456
457static inline void SlWriteUint64(uint64_t x)
458{
459 SlWriteUint32(static_cast<uint32_t>(x >> 32));
460 SlWriteUint32(static_cast<uint32_t>(x));
461}
462
467static inline ChunkId SlReadChunkId()
468{
469 ChunkId label{};
470 for (uint8_t &b : label) b = SlReadByte();
471 return label;
472}
473
483static uint SlReadSimpleGamma()
484{
485 uint i = SlReadByte();
486 if (HasBit(i, 7)) {
487 i &= ~0x80;
488 if (HasBit(i, 6)) {
489 i &= ~0x40;
490 if (HasBit(i, 5)) {
491 i &= ~0x20;
492 if (HasBit(i, 4)) {
493 i &= ~0x10;
494 if (HasBit(i, 3)) {
495 SlErrorCorrupt("Unsupported gamma");
496 }
497 i = SlReadByte(); // 32 bits only.
498 }
499 i = (i << 8) | SlReadByte();
500 }
501 i = (i << 8) | SlReadByte();
502 }
503 i = (i << 8) | SlReadByte();
504 }
505 return i;
506}
507
524
525static void SlWriteSimpleGamma(size_t i)
526{
527 if (i >= (1 << 7)) {
528 if (i >= (1 << 14)) {
529 if (i >= (1 << 21)) {
530 if (i >= (1 << 28)) {
531 assert(i <= UINT32_MAX); // We can only support 32 bits for now.
532 SlWriteByte(static_cast<uint8_t>(0xF0));
533 SlWriteByte(static_cast<uint8_t>(i >> 24));
534 } else {
535 SlWriteByte(static_cast<uint8_t>(0xE0 | (i >> 24)));
536 }
537 SlWriteByte(static_cast<uint8_t>(i >> 16));
538 } else {
539 SlWriteByte(static_cast<uint8_t>(0xC0 | (i >> 16)));
540 }
541 SlWriteByte(static_cast<uint8_t>(i >> 8));
542 } else {
543 SlWriteByte(static_cast<uint8_t>(0x80 | (i >> 8)));
544 }
545 }
546 SlWriteByte(static_cast<uint8_t>(i));
547}
548
554static inline uint SlGetGammaLength(size_t i)
555{
556 return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21)) + (i >= (1 << 28));
557}
558
559static inline uint SlReadSparseIndex()
560{
561 return SlReadSimpleGamma();
562}
563
564static inline void SlWriteSparseIndex(uint index)
565{
566 SlWriteSimpleGamma(index);
567}
568
569static inline uint SlReadArrayLength()
570{
571 return SlReadSimpleGamma();
572}
573
574static inline void SlWriteArrayLength(size_t length)
575{
576 SlWriteSimpleGamma(length);
577}
578
579static inline uint SlGetArrayLength(size_t length)
580{
581 return SlGetGammaLength(length);
582}
583
589 static constexpr uint8_t HAS_FIELD_LENGTH_BIT = 4;
590 uint8_t storage{};
591
594
600 SavegameFileType(VarFileType file_type, bool has_field_length = false) : storage(to_underlying(file_type))
601 {
602 /* 0 is not allowed as it's the end-of-table marker, larger is not allowed due to the field length bit. */
603 assert(IsInsideMM(to_underlying(file_type), 1, 1 << HAS_FIELD_LENGTH_BIT));
604 AssignBit(this->storage, HAS_FIELD_LENGTH_BIT, has_field_length);
605 }
606
611 constexpr bool IsEnd() const { return storage == 0; }
612
617 constexpr bool HasFieldLength() const
618 {
619 assert(!this->IsEnd());
620 return HasBit(storage, HAS_FIELD_LENGTH_BIT);
621 }
622
627 constexpr VarFileType Type() const
628 {
629 assert(!this->IsEnd());
630 return static_cast<VarFileType>(GB(storage, 0, HAS_FIELD_LENGTH_BIT));
631 }
632};
633
640{
641 switch (sld.cmd) {
643 return sld.conv.file;
644
648 return { sld.conv.file, true };
649
652
656
658 return VarFileType::U8;
659
662 return { VarFileType::Struct, true };
663
664 default: NOT_REACHED();
665 }
666}
667
674static inline uint SlCalcConvMemLen(VarMemType conv)
675{
676 switch (conv) {
677 case VarMemType::Bool: return sizeof(bool);
678 case VarMemType::I8: return sizeof(int8_t);
679 case VarMemType::U8: return sizeof(uint8_t);
680 case VarMemType::I16: return sizeof(int16_t);
681 case VarMemType::U16: return sizeof(uint16_t);
682 case VarMemType::I32: return sizeof(int32_t);
683 case VarMemType::U32: return sizeof(uint32_t);
684 case VarMemType::I64: return sizeof(int64_t);
685 case VarMemType::U64: return sizeof(uint64_t);
686 case VarMemType::Null: return 0;
687 case VarMemType::Label: return sizeof(BaseLabel);
688
689 case VarMemType::Str:
690 return SlReadArrayLength();
691
692 case VarMemType::Name:
693 default:
694 NOT_REACHED();
695 }
696}
697
704static inline uint8_t SlCalcConvFileLen(VarType conv)
705{
706 switch (conv.file) {
707 case VarFileType::I8: return sizeof(int8_t);
708 case VarFileType::U8: return sizeof(uint8_t);
709 case VarFileType::I16: return sizeof(int16_t);
710 case VarFileType::U16: return sizeof(uint16_t);
711 case VarFileType::I32: return sizeof(int32_t);
712 case VarFileType::U32: return sizeof(uint32_t);
713 case VarFileType::I64: return sizeof(int64_t);
714 case VarFileType::U64: return sizeof(uint64_t);
715 case VarFileType::StringID: return sizeof(uint16_t);
716
718 return SlReadArrayLength();
719
721 default:
722 NOT_REACHED();
723 }
724}
725
730static inline size_t SlCalcRefLen()
731{
733}
734
735void SlSetArrayIndex(uint index)
736{
737 _sl.need_length = NeedLength::WantLength;
738 _sl.array_index = index;
739}
740
741static size_t _next_offs;
742
748{
749 /* After reading in the whole array inside the loop
750 * we must have read in all the data, so we must be at end of current block. */
751 if (_next_offs != 0 && _sl.reader->GetSize() != _next_offs) {
752 SlErrorCorruptFmt("Invalid chunk size iterating array - expected to be at position {}, actually at {}", _next_offs, _sl.reader->GetSize());
753 }
754
755 for (;;) {
756 uint length = SlReadArrayLength();
757 if (length == 0) {
758 assert(!_sl.expect_table_header);
759 _next_offs = 0;
760 return -1;
761 }
762
763 _sl.obj_len = --length;
764 _next_offs = _sl.reader->GetSize() + length;
765
766 if (_sl.expect_table_header) {
767 _sl.expect_table_header = false;
768 return INT32_MAX;
769 }
770
771 int index;
772 switch (_sl.chunk_type) {
774 case ChunkType::SparseArray: index = static_cast<int>(SlReadSparseIndex()); break;
775 case ChunkType::Table:
776 case ChunkType::Array: index = _sl.array_index++; break;
777 default:
778 Debug(Facility::Sl, Severity::Critical, "SlIterateArray error");
779 return -1; // error
780 }
781
782 if (length != 0) return index;
783 }
784}
785
790{
791 while (SlIterateArray() != -1) {
792 SlSkipBytes(_next_offs - _sl.reader->GetSize());
793 }
794}
795
801void SlSetLength(size_t length)
802{
803 assert(_sl.action == SaveLoadAction::Save);
804
805 switch (_sl.need_length) {
807 _sl.need_length = NeedLength::None;
808 if ((_sl.chunk_type == ChunkType::Table || _sl.chunk_type == ChunkType::SparseTable) && _sl.expect_table_header) {
809 _sl.expect_table_header = false;
810 SlWriteArrayLength(length + 1);
811 break;
812 }
813
814 switch (_sl.chunk_type) {
815 case ChunkType::Riff:
816 /* Ugly encoding of >16M RIFF chunks
817 * The lower 24 bits are normal
818 * The uppermost 4 bits are bits 24:27 */
819 assert(length < (1 << 28));
820 SlWriteUint32((uint32_t)((length & 0xFFFFFF) | ((length >> 24) << 28)));
821 break;
822 case ChunkType::Table:
823 case ChunkType::Array:
824 assert(_sl.last_array_index <= _sl.array_index);
825 while (++_sl.last_array_index <= _sl.array_index) {
826 SlWriteArrayLength(1);
827 }
828 SlWriteArrayLength(length + 1);
829 break;
832 SlWriteArrayLength(length + 1 + SlGetArrayLength(_sl.array_index)); // Also include length of sparse index.
833 SlWriteSparseIndex(_sl.array_index);
834 break;
835 default: NOT_REACHED();
836 }
837 break;
838
840 _sl.obj_len += static_cast<int>(length);
841 break;
842
843 default: NOT_REACHED();
844 }
845}
846
853static void SlCopyBytes(void *ptr, size_t length)
854{
855 uint8_t *p = static_cast<uint8_t *>(ptr);
856
857 switch (_sl.action) {
860 for (; length != 0; length--) *p++ = SlReadByte();
861 break;
863 for (; length != 0; length--) SlWriteByte(*p++);
864 break;
865 default: NOT_REACHED();
866 }
867}
868
874{
875 return _sl.obj_len;
876}
877
885int64_t ReadValue(const void *ptr, VarMemType conv)
886{
887 switch (conv) {
888 case VarMemType::Bool: return (*static_cast<const bool *>(ptr) != 0);
889 case VarMemType::I8: return *static_cast<const int8_t *>(ptr);
890 case VarMemType::U8: return *static_cast<const uint8_t *>(ptr);
891 case VarMemType::I16: return *static_cast<const int16_t *>(ptr);
892 case VarMemType::U16: return *static_cast<const uint16_t *>(ptr);
893 case VarMemType::I32: return *static_cast<const int32_t *>(ptr);
894 case VarMemType::U32: return *static_cast<const uint32_t *>(ptr);
895 case VarMemType::I64: return *static_cast<const int64_t *>(ptr);
896 case VarMemType::U64: return *static_cast<const uint64_t *>(ptr);
897 case VarMemType::Null: return 0;
898 default: NOT_REACHED();
899 }
900}
901
909void WriteValue(void *ptr, VarMemType conv, int64_t val)
910{
911 switch (conv) {
912 case VarMemType::Bool: *static_cast<bool *>(ptr) = (val != 0); break;
913 case VarMemType::I8: *static_cast<int8_t *>(ptr) = val; break;
914 case VarMemType::U8: *static_cast<uint8_t *>(ptr) = val; break;
915 case VarMemType::I16: *static_cast<int16_t *>(ptr) = val; break;
916 case VarMemType::U16: *static_cast<uint16_t *>(ptr) = val; break;
917 case VarMemType::I32: *static_cast<int32_t *>(ptr) = val; break;
918 case VarMemType::U32: *static_cast<uint32_t *>(ptr) = val; break;
919 case VarMemType::I64: *static_cast<int64_t *>(ptr) = val; break;
920 case VarMemType::U64: *static_cast<uint64_t *>(ptr) = val; break;
921 case VarMemType::Name: *reinterpret_cast<std::string *>(ptr) = CopyFromOldName(static_cast<StringID>(val)); break;
922 case VarMemType::Null: break;
923 default: NOT_REACHED();
924 }
925}
926
935static void SlSaveLoadConv(void *ptr, VarType conv)
936{
937 switch (_sl.action) {
939 if (conv == VarTypes::LABEL) {
940 /* Labels are written in reverse order as that is the way GrfIDs used to be written.
941 * Changing the order means changing external applications that extract this data. */
942 BaseLabel *label = static_cast<BaseLabel *>(ptr);
943 for (auto it = label->rbegin(); it != label->rend(); it++) SlWriteByte(*it);
944 break;
945 }
946
947 int64_t x = ReadValue(ptr, conv.mem);
948
949 /* Write the value to the file and check if its value is in the desired range */
950 switch (conv.file) {
951 case VarFileType::I8:
952 assert(x >= -128 && x <= 127);
953 SlWriteByte(x);
954 break;
955
956 case VarFileType::U8:
957 assert(x >= 0 && x <= 255);
958 SlWriteByte(x);
959 break;
960
961 case VarFileType::I16:
962 assert(x >= -32768 && x <= 32767);
963 SlWriteUint16(x);
964 break;
965
967 case VarFileType::U16:
968 assert(x >= 0 && x <= 65535);
969 SlWriteUint16(x);
970 break;
971
972 case VarFileType::I32:
973 case VarFileType::U32:
974 SlWriteUint32(static_cast<uint32_t>(x));
975 break;
976
977 case VarFileType::I64:
978 case VarFileType::U64:
979 SlWriteUint64(x);
980 break;
981
982 default: NOT_REACHED();
983 }
984 break;
985 }
988 if (conv == VarTypes::LABEL) {
989 /* Labels are written in reverse order as that is the way GrfIDs used to be written.
990 * Changing the order means changing external applications that extract this data.
991 * The road/rail type labels were in forward order. They are fixed when needed in
992 * their respective loaders. */
993 BaseLabel *label = static_cast<BaseLabel *>(ptr);
994 for (auto it = label->rbegin(); it != label->rend(); it++) *it = SlReadByte();
995 break;
996 }
997
998 int64_t x;
999 /* Read a value from the file */
1000 switch (conv.file) {
1001 case VarFileType::I8: x = static_cast<int8_t>(SlReadByte()); break;
1002 case VarFileType::U8: x = static_cast<uint8_t>(SlReadByte()); break;
1003 case VarFileType::I16: x = static_cast<int16_t>(SlReadUint16()); break;
1004 case VarFileType::U16: x = static_cast<uint16_t>(SlReadUint16()); break;
1005 case VarFileType::I32: x = static_cast<int32_t>(SlReadUint32()); break;
1006 case VarFileType::U32: x = static_cast<uint32_t>(SlReadUint32()); break;
1007 case VarFileType::I64: x = static_cast<int64_t>(SlReadUint64()); break;
1008 case VarFileType::U64: x = static_cast<uint64_t>(SlReadUint64()); break;
1009 case VarFileType::StringID: x = RemapOldStringID(static_cast<StringID>(SlReadUint16())).base(); break;
1010 default: NOT_REACHED();
1011 }
1012
1013 /* Write The value to the struct. These ARE endian safe. */
1014 WriteValue(ptr, conv.mem, x);
1015 break;
1016 }
1017 case SaveLoadAction::Ptrs: break;
1018 case SaveLoadAction::Null: break;
1019 default: NOT_REACHED();
1020 }
1021}
1022
1030static inline size_t SlCalcStdStringLen(const void *ptr)
1031{
1032 const std::string *str = reinterpret_cast<const std::string *>(ptr);
1033
1034 size_t len = str->length();
1035 return len + SlGetArrayLength(len); // also include the length of the index
1036}
1037
1038
1047void FixSCCEncoded(std::string &str, bool fix_code)
1048{
1049 if (str.empty()) return;
1050
1051 /* We need to convert from old escape-style encoding to record separator encoding.
1052 * Initial `<SCC_ENCODED><STRINGID>` stays the same.
1053 *
1054 * `:<SCC_ENCODED><STRINGID>` becomes `<RS><SCC_ENCODED><STRINGID>`
1055 * `:<HEX>` becomes `<RS><SCC_ENCODED_NUMERIC><HEX>`
1056 * `:"<STRING>"` becomes `<RS><SCC_ENCODED_STRING><STRING>`
1057 */
1058 std::string result;
1059 StringBuilder builder(result);
1060
1061 bool is_encoded = false; // Set if we determine by the presence of SCC_ENCODED that the string is an encoded string.
1062 bool in_string = false; // Set if we in a string, between double-quotes.
1063 bool need_type = true; // Set if a parameter type needs to be emitted.
1064
1065 StringConsumer consumer(str);
1066 while (consumer.AnyBytesLeft()) {
1067 char32_t c;
1068 if (auto r = consumer.TryReadUtf8(); r.has_value()) {
1069 c = *r;
1070 } else {
1071 break;
1072 }
1073 if (c == SCC_ENCODED || (fix_code && (c == 0xE028 || c == 0xE02A))) {
1074 builder.PutUtf8(SCC_ENCODED);
1075 need_type = false;
1076 is_encoded = true;
1077 continue;
1078 }
1079
1080 /* If the first character is not SCC_ENCODED then we don't have to do any conversion. */
1081 if (!is_encoded) return;
1082
1083 if (c == '"') {
1084 in_string = !in_string;
1085 if (in_string && need_type) {
1086 /* Started a new string parameter. */
1087 builder.PutUtf8(SCC_ENCODED_STRING);
1088 need_type = false;
1089 }
1090 continue;
1091 }
1092
1093 if (!in_string && c == ':') {
1094 builder.PutUtf8(SCC_RECORD_SEPARATOR);
1095 need_type = true;
1096 continue;
1097 }
1098 if (need_type) {
1099 /* Started a new numeric parameter. */
1101 need_type = false;
1102 }
1103
1104 builder.PutUtf8(c);
1105 }
1106
1107 str = std::move(result);
1108}
1109
1114void FixSCCEncodedNegative(std::string &str)
1115{
1116 if (str.empty()) return;
1117
1118 StringConsumer consumer(str);
1119
1120 /* Check whether this is an encoded string */
1121 if (!consumer.ReadUtf8If(SCC_ENCODED)) return;
1122
1123 std::string result;
1124 StringBuilder builder(result);
1125 builder.PutUtf8(SCC_ENCODED);
1126 while (consumer.AnyBytesLeft()) {
1127 /* Copy until next record */
1128 builder.Put(consumer.ReadUntilUtf8(SCC_RECORD_SEPARATOR, StringConsumer::READ_ONE_SEPARATOR));
1129
1130 /* Check whether this is a numeric parameter */
1131 if (!consumer.ReadUtf8If(SCC_ENCODED_NUMERIC)) continue;
1133
1134 /* First try unsigned */
1135 if (auto u = consumer.TryReadIntegerBase<uint64_t>(16); u.has_value()) {
1136 builder.PutIntegerBase<uint64_t>(*u, 16);
1137 } else {
1138 /* Read as signed, store as unsigned */
1139 auto s = consumer.ReadIntegerBase<int64_t>(16);
1140 builder.PutIntegerBase<uint64_t>(static_cast<uint64_t>(s), 16);
1141 }
1142 }
1143
1144 str = std::move(result);
1145}
1146
1153void SlReadString(std::string &str, size_t length)
1154{
1155 str.resize(length);
1156 SlCopyBytes(str.data(), length);
1157}
1158
1164static void SlStdString(void *ptr, VarType conv)
1165{
1166 std::string *str = reinterpret_cast<std::string *>(ptr);
1167
1168 switch (_sl.action) {
1169 case SaveLoadAction::Save: {
1170 size_t len = str->length();
1171 SlWriteArrayLength(len);
1172 SlCopyBytes(const_cast<void *>(static_cast<const void *>(str->data())), len);
1173 break;
1174 }
1175
1177 case SaveLoadAction::Load: {
1178 size_t len = SlReadArrayLength();
1179 if (conv.mem == VarMemType::Null) {
1180 SlSkipBytes(len);
1181 return;
1182 }
1183
1184 SlReadString(*str, len);
1185
1191 }
1193 }
1194
1195 case SaveLoadAction::Ptrs: break;
1196 case SaveLoadAction::Null: break;
1197 default: NOT_REACHED();
1198 }
1199}
1200
1209static void SlCopyInternal(void *object, size_t length, VarType conv)
1210{
1211 if (conv.mem == VarMemType::Null) {
1212 assert(_sl.action != SaveLoadAction::Save); // Use SaveLoadType::Null if you want to write null-bytes
1213 SlSkipBytes(length * SlCalcConvFileLen(conv));
1214 return;
1215 }
1216
1217 /* NOTICE - handle some buggy stuff, in really old versions everything was saved
1218 * as a byte-type. So detect this, and adjust object size accordingly */
1220 /* all objects except difficulty settings */
1221 if (conv == VarTypes::I16 || conv == VarTypes::U16 || conv == VarTypes::STRINGID ||
1222 conv == VarTypes::I32 || conv == VarTypes::U32) {
1223 SlCopyBytes(object, length * SlCalcConvFileLen(conv));
1224 return;
1225 }
1226 /* used for conversion of Money 32bit->64bit */
1227 if (conv.file == VarFileType::I32 && conv.mem == VarMemType::I64) {
1228 for (uint i = 0; i < length; i++) {
1229 static_cast<int64_t *>(object)[i] = std::byteswap(SlReadUint32());
1230 }
1231 return;
1232 }
1233 }
1234
1235 /* If the size of elements is 1 byte both in file and memory, no special
1236 * conversion is needed, use specialized copy-copy function to speed up things */
1237 if (conv == VarTypes::I8 || conv == VarTypes::U8) {
1238 SlCopyBytes(object, length);
1239 } else {
1240 uint8_t *a = static_cast<uint8_t *>(object);
1241 uint8_t mem_size = SlCalcConvMemLen(conv.mem);
1242
1243 for (; length != 0; length --) {
1244 SlSaveLoadConv(a, conv);
1245 a += mem_size; // get size
1246 }
1247 }
1248}
1249
1258void SlCopy(void *object, size_t length, VarType conv)
1259{
1260 assert(object != nullptr); // Use SlSkipBytes instead
1261 if (_sl.action == SaveLoadAction::Ptrs || _sl.action == SaveLoadAction::Null) return;
1262
1263 /* Automatically calculate the length? */
1264 if (_sl.need_length != NeedLength::None) {
1265 SlSetLength(length * SlCalcConvFileLen(conv));
1266 /* Determine length only? */
1267 if (_sl.need_length == NeedLength::CalcLength) return;
1268 }
1269
1270 SlCopyInternal(object, length, conv);
1271}
1272
1279static inline size_t SlCalcArrayLen(size_t length, VarType conv)
1280{
1281 return SlCalcConvFileLen(conv) * length + SlGetArrayLength(length);
1282}
1283
1290static void SlArray(void *array, size_t length, VarType conv)
1291{
1292 switch (_sl.action) {
1294 SlWriteArrayLength(length);
1295 SlCopyInternal(array, length, conv);
1296 return;
1297
1299 case SaveLoadAction::Load: {
1301 size_t sv_length = SlReadArrayLength();
1302 if (conv.mem == VarMemType::Null) {
1303 /* We don't know this field, so we assume the length in the savegame is correct. */
1304 length = sv_length;
1305 } else if (sv_length != length) {
1306 /* If the SLE_ARR changes size, a savegame bump is required
1307 * and the developer should have written conversion lines.
1308 * Error out to make this more visible. */
1309 SlErrorCorrupt("Fixed-length array is of wrong length");
1310 }
1311 }
1312
1313 SlCopyInternal(array, length, conv);
1314 return;
1315 }
1316
1319 return;
1320
1321 default:
1322 NOT_REACHED();
1323 }
1324}
1325
1336static uint32_t ReferenceToInt(const void *obj, SLRefType rt)
1337{
1338 assert(_sl.action == SaveLoadAction::Save);
1339
1340 if (obj == nullptr) return 0;
1341
1342 switch (rt) {
1343 case SLRefType::OldVehicle: // Old vehicles we save as new ones
1344 case SLRefType::Vehicle: return static_cast<const Vehicle *>(obj)->index + 1;
1345 case SLRefType::Station: return static_cast<const Station *>(obj)->index + 1;
1346 case SLRefType::Town: return static_cast<const Town *>(obj)->index + 1;
1347 case SLRefType::RoadStop: return static_cast<const RoadStop *>(obj)->index + 1;
1348 case SLRefType::CargoPacket: return static_cast<const CargoPacket *>(obj)->index + 1;
1349 case SLRefType::OrderList: return static_cast<const OrderList *>(obj)->index + 1;
1350 case SLRefType::Storage: return static_cast<const PersistentStorage *>(obj)->index + 1;
1351 case SLRefType::LinkGraph: return static_cast<const LinkGraph *>(obj)->index + 1;
1352 case SLRefType::LinkGraphJob: return static_cast<const LinkGraphJob *>(obj)->index + 1;
1353 default: NOT_REACHED();
1354 }
1355}
1356
1367static void *IntToReference(size_t index, SLRefType rt)
1368{
1369 static_assert(sizeof(size_t) <= sizeof(void *));
1370
1371 assert(_sl.action == SaveLoadAction::Ptrs);
1372
1373 /* After version 4.3 SLRefType::OldVehicle is saved as SLRefType::Vehicle,
1374 * and should be loaded like that */
1376 rt = SLRefType::Vehicle;
1377 }
1378
1379 /* No need to look up nullptr pointers, just return immediately */
1380 if (index == (rt == SLRefType::OldVehicle ? 0xFFFF : 0)) return nullptr;
1381
1382 /* Correct index. Old vehicles were saved differently:
1383 * invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
1384 if (rt != SLRefType::OldVehicle) index--;
1385
1386 switch (rt) {
1388 if (OrderList::IsValidID(index)) return OrderList::Get(index);
1389 SlErrorCorrupt("Referencing invalid OrderList");
1390
1392 case SLRefType::Vehicle:
1393 if (Vehicle::IsValidID(index)) return Vehicle::Get(index);
1394 SlErrorCorrupt("Referencing invalid Vehicle");
1395
1396 case SLRefType::Station:
1397 if (Station::IsValidID(index)) return Station::Get(index);
1398 SlErrorCorrupt("Referencing invalid Station");
1399
1400 case SLRefType::Town:
1401 if (Town::IsValidID(index)) return Town::Get(index);
1402 SlErrorCorrupt("Referencing invalid Town");
1403
1405 if (RoadStop::IsValidID(index)) return RoadStop::Get(index);
1406 SlErrorCorrupt("Referencing invalid RoadStop");
1407
1409 if (CargoPacket::IsValidID(index)) return CargoPacket::Get(index);
1410 SlErrorCorrupt("Referencing invalid CargoPacket");
1411
1412 case SLRefType::Storage:
1413 if (PersistentStorage::IsValidID(index)) return PersistentStorage::Get(index);
1414 SlErrorCorrupt("Referencing invalid PersistentStorage");
1415
1417 if (LinkGraph::IsValidID(index)) return LinkGraph::Get(index);
1418 SlErrorCorrupt("Referencing invalid LinkGraph");
1419
1421 if (LinkGraphJob::IsValidID(index)) return LinkGraphJob::Get(index);
1422 SlErrorCorrupt("Referencing invalid LinkGraphJob");
1423
1424 default: NOT_REACHED();
1425 }
1426}
1427
1433void SlSaveLoadRef(void *ptr, VarType conv)
1434{
1435 switch (_sl.action) {
1437 SlWriteUint32(ReferenceToInt(*static_cast<void **>(ptr), conv.ref));
1438 break;
1441 *static_cast<size_t *>(ptr) = IsSavegameVersionBefore(SaveLoadVersion::MoreCargoPackets) ? SlReadUint16() : SlReadUint32();
1442 break;
1444 *static_cast<void **>(ptr) = IntToReference(*static_cast<size_t *>(ptr), conv.ref);
1445 break;
1447 *static_cast<void **>(ptr) = nullptr;
1448 break;
1449 default: NOT_REACHED();
1450 }
1451}
1452
1456template <template <typename, typename> typename Tstorage, typename Tvar, typename Tallocator = std::allocator<Tvar>>
1458 typedef Tstorage<Tvar, Tallocator> SlStorageT;
1459public:
1467 static size_t SlCalcLen(const void *storage, VarType conv, SaveLoadType cmd = SaveLoadType::Variable)
1468 {
1469 assert(cmd == SaveLoadType::Variable || cmd == SaveLoadType::Reference);
1470
1471 const SlStorageT *list = static_cast<const SlStorageT *>(storage);
1472
1473 int type_size = SlGetArrayLength(list->size());
1474 int item_size = SlCalcConvFileLen(cmd == SaveLoadType::Variable ? conv : VarType{VarFileType::U32, {}});
1475 return list->size() * item_size + type_size;
1476 }
1477
1478 static void SlSaveLoadMember(SaveLoadType cmd, Tvar *item, VarType conv)
1479 {
1480 switch (cmd) {
1481 case SaveLoadType::Variable: SlSaveLoadConv(item, conv); break;
1482 case SaveLoadType::Reference: SlSaveLoadRef(item, conv); break;
1483 case SaveLoadType::String: SlStdString(item, conv); break;
1484 default:
1485 NOT_REACHED();
1486 }
1487 }
1488
1495 static void SlSaveLoad(void *storage, VarType conv, SaveLoadType cmd = SaveLoadType::Variable)
1496 {
1497 assert(cmd == SaveLoadType::Variable || cmd == SaveLoadType::Reference || cmd == SaveLoadType::String);
1498
1499 SlStorageT *list = static_cast<SlStorageT *>(storage);
1500
1501 switch (_sl.action) {
1503 SlWriteArrayLength(list->size());
1504
1505 for (auto &item : *list) {
1506 SlSaveLoadMember(cmd, &item, conv);
1507 }
1508 break;
1509
1511 case SaveLoadAction::Load: {
1512 size_t length;
1513 switch (cmd) {
1514 case SaveLoadType::Variable: length = IsSavegameVersionBefore(SaveLoadVersion::SaveloadListLength) ? SlReadUint32() : SlReadArrayLength(); break;
1515 case SaveLoadType::Reference: length = IsSavegameVersionBefore(SaveLoadVersion::MoreCargoPackets) ? SlReadUint16() : IsSavegameVersionBefore(SaveLoadVersion::SaveloadListLength) ? SlReadUint32() : SlReadArrayLength(); break;
1516 case SaveLoadType::String: length = SlReadArrayLength(); break;
1517 default: NOT_REACHED();
1518 }
1519
1520 list->clear();
1521 if constexpr (std::is_same_v<SlStorageT, std::vector<Tvar, Tallocator>>) {
1522 list->reserve(length);
1523 }
1524
1525 /* Load each value and push to the end of the storage. */
1526 for (size_t i = 0; i < length; i++) {
1527 Tvar &data = list->emplace_back();
1528 SlSaveLoadMember(cmd, &data, conv);
1529 }
1530 break;
1531 }
1532
1534 for (auto &item : *list) {
1535 SlSaveLoadMember(cmd, &item, conv);
1536 }
1537 break;
1538
1540 list->clear();
1541 break;
1542
1543 default: NOT_REACHED();
1544 }
1545 }
1546};
1547
1554static inline size_t SlCalcRefListLen(const void *list, VarType conv)
1555{
1557}
1558
1564static void SlRefList(void *list, VarType conv)
1565{
1566 /* Automatically calculate the length? */
1567 if (_sl.need_length != NeedLength::None) {
1568 SlSetLength(SlCalcRefListLen(list, conv));
1569 /* Determine length only? */
1570 if (_sl.need_length == NeedLength::CalcLength) return;
1571 }
1572
1574}
1575
1582static size_t SlCalcRefVectorLen(const void *vector, VarType conv)
1583{
1585}
1586
1592static void SlRefVector(void *vector, VarType conv)
1593{
1594 /* Automatically calculate the length? */
1595 if (_sl.need_length != NeedLength::None) {
1596 SlSetLength(SlCalcRefVectorLen(vector, conv));
1597 /* Determine length only? */
1598 if (_sl.need_length == NeedLength::CalcLength) return;
1599 }
1600
1602}
1603
1610static inline size_t SlCalcVectorLen(const void *vector, VarType conv)
1611{
1612 switch (conv.mem) {
1613 case VarMemType::Bool: NOT_REACHED(); // Not supported
1622
1623 case VarMemType::Str:
1624 /* Strings are a length-prefixed field type in the savegame table format,
1625 * these may not be directly stored in another length-prefixed container type. */
1626 NOT_REACHED();
1627
1628 default: NOT_REACHED();
1629 }
1630}
1631
1637static void SlVector(void *vector, VarType conv)
1638{
1639 switch (conv.mem) {
1640 case VarMemType::Bool: NOT_REACHED(); // Not supported
1649
1650 case VarMemType::Str:
1651 /* Strings are a length-prefixed field type in the savegame table format,
1652 * these may not be directly stored in another length-prefixed container type.
1653 * This is permitted for load-related actions, because invalid fields of this type are present
1654 * from SaveLoadVersion::CompanyAllowList up to SaveLoadVersion::CompanyAllowListV2. */
1655 assert(_sl.action != SaveLoadAction::Save);
1657 break;
1658
1659 default: NOT_REACHED();
1660 }
1661}
1662
1668static inline bool SlIsObjectValidInSavegame(const SaveLoad &sld)
1669{
1670 return (_sl_version >= sld.version_from && _sl_version < sld.version_to);
1671}
1672
1678static size_t SlCalcTableHeader(const SaveLoadTable &slt)
1679{
1680 size_t length = 0;
1681
1682 for (auto &sld : slt) {
1683 if (!SlIsObjectValidInSavegame(sld)) continue;
1684
1686 length += SlCalcStdStringLen(&sld.name);
1687 }
1688
1689 length += SlCalcConvFileLen(VarTypes::U8); // End-of-list entry.
1690
1691 for (auto &sld : slt) {
1692 if (!SlIsObjectValidInSavegame(sld)) continue;
1693 if (sld.cmd == SaveLoadType::StructList || sld.cmd == SaveLoadType::Struct) {
1694 length += SlCalcTableHeader(sld.handler->GetDescription());
1695 }
1696 }
1697
1698 return length;
1699}
1700
1707size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt)
1708{
1709 size_t length = 0;
1710
1711 /* Need to determine the length and write a length tag. */
1712 for (auto &sld : slt) {
1713 length += SlCalcObjMemberLength(object, sld);
1714 }
1715 return length;
1716}
1717
1718size_t SlCalcObjMemberLength(const void *object, const SaveLoad &sld)
1719{
1720 assert(_sl.action == SaveLoadAction::Save);
1721
1722 if (!SlIsObjectValidInSavegame(sld)) return 0;
1723
1724 switch (sld.cmd) {
1727 case SaveLoadType::Array: return SlCalcArrayLen(sld.length, sld.conv);
1730 case SaveLoadType::Vector: return SlCalcVectorLen(GetVariableAddress(object, sld), sld.conv);
1732 case SaveLoadType::SaveByte: return 1; // a byte is logically of size 1
1733 case SaveLoadType::Null: return SlCalcConvFileLen(sld.conv) * sld.length;
1734
1737 NeedLength old_need_length = _sl.need_length;
1738 size_t old_obj_len = _sl.obj_len;
1739
1740 _sl.need_length = NeedLength::CalcLength;
1741 _sl.obj_len = 0;
1742
1743 /* Pretend that we are saving to collect the object size. Other
1744 * means are difficult, as we don't know the length of the list we
1745 * are about to store. */
1746 sld.handler->Save(const_cast<void *>(object));
1747 size_t length = _sl.obj_len;
1748
1749 _sl.obj_len = old_obj_len;
1750 _sl.need_length = old_need_length;
1751
1752 if (sld.cmd == SaveLoadType::Struct) {
1753 length += SlGetArrayLength(1);
1754 }
1755
1756 return length;
1757 }
1758
1759 default: NOT_REACHED();
1760 }
1761 return 0;
1762}
1763
1764static bool SlObjectMember(void *object, const SaveLoad &sld)
1765{
1766 if (!SlIsObjectValidInSavegame(sld)) return false;
1767
1768 switch (sld.cmd) {
1775 case SaveLoadType::String: {
1776 void *ptr = GetVariableAddress(object, sld);
1777
1778 switch (sld.cmd) {
1779 case SaveLoadType::Variable: SlSaveLoadConv(ptr, sld.conv); break;
1780 case SaveLoadType::Reference: SlSaveLoadRef(ptr, sld.conv); break;
1781 case SaveLoadType::Array: SlArray(ptr, sld.length, sld.conv); break;
1782 case SaveLoadType::ReferenceList: SlRefList(ptr, sld.conv); break;
1783 case SaveLoadType::ReferenceVector: SlRefVector(ptr, sld.conv); break;
1784 case SaveLoadType::Vector: SlVector(ptr, sld.conv); break;
1785 case SaveLoadType::String: SlStdString(ptr, sld.conv); break;
1786 default: NOT_REACHED();
1787 }
1788 break;
1789 }
1790
1791 /* SaveLoadType::SaveByte writes a value to the savegame to identify the type of an object.
1792 * When loading, the value is read explicitly with SlReadByte() to determine which
1793 * object description to use. */
1795 void *ptr = GetVariableAddress(object, sld);
1796
1797 switch (_sl.action) {
1798 case SaveLoadAction::Save: SlWriteByte(*static_cast<uint8_t *>(ptr)); break;
1802 case SaveLoadAction::Null: break;
1803 default: NOT_REACHED();
1804 }
1805 break;
1806 }
1807
1808 case SaveLoadType::Null: {
1809 assert(sld.conv.mem == VarMemType::Null);
1810
1811 switch (_sl.action) {
1814 case SaveLoadAction::Save: for (int i = 0; i < SlCalcConvFileLen(sld.conv) * sld.length; i++) SlWriteByte(0); break;
1816 case SaveLoadAction::Null: break;
1817 default: NOT_REACHED();
1818 }
1819 break;
1820 }
1821
1824 switch (_sl.action) {
1825 case SaveLoadAction::Save: {
1826 if (sld.cmd == SaveLoadType::Struct) {
1827 /* Store in the savegame if this struct was written or not. */
1828 SlSetStructListLength(SlCalcObjMemberLength(object, sld) > SlGetArrayLength(1) ? 1 : 0);
1829 }
1830 sld.handler->Save(object);
1831 break;
1832 }
1833
1837 }
1838 sld.handler->LoadCheck(object);
1839 break;
1840 }
1841
1842 case SaveLoadAction::Load: {
1845 }
1846 sld.handler->Load(object);
1847 break;
1848 }
1849
1851 sld.handler->FixPointers(object);
1852 break;
1853
1854 case SaveLoadAction::Null: break;
1855 default: NOT_REACHED();
1856 }
1857 break;
1858
1859 default: NOT_REACHED();
1860 }
1861 return true;
1862}
1863
1868void SlSetStructListLength(size_t length)
1869{
1870 /* Automatically calculate the length? */
1871 if (_sl.need_length != NeedLength::None) {
1872 SlSetLength(SlGetArrayLength(length));
1873 if (_sl.need_length == NeedLength::CalcLength) return;
1874 }
1875
1876 SlWriteArrayLength(length);
1877}
1878
1884size_t SlGetStructListLength(size_t limit)
1885{
1886 size_t length = SlReadArrayLength();
1887 if (length > limit) SlErrorCorrupt("List exceeds storage size");
1888
1889 return length;
1890}
1891
1897void SlObject(void *object, const SaveLoadTable &slt)
1898{
1899 /* Automatically calculate the length? */
1900 if (_sl.need_length != NeedLength::None) {
1901 SlSetLength(SlCalcObjLength(object, slt));
1902 if (_sl.need_length == NeedLength::CalcLength) return;
1903 }
1904
1905 for (auto &sld : slt) {
1906 SlObjectMember(object, sld);
1907 }
1908}
1909
1915 void Save(void *) const override
1916 {
1917 NOT_REACHED();
1918 }
1919
1920 void Load(void *object) const override
1921 {
1922 size_t length = SlGetStructListLength(UINT32_MAX);
1923 for (; length > 0; length--) {
1924 SlObject(object, this->GetLoadDescription());
1925 }
1926 }
1927
1928 void LoadCheck(void *object) const override
1929 {
1930 this->Load(object);
1931 }
1932
1934 {
1935 return {};
1936 }
1937
1939 {
1940 NOT_REACHED();
1941 }
1942};
1943
1950std::vector<SaveLoad> SlTableHeader(const SaveLoadTable &slt)
1951{
1952 /* You can only use SlTableHeader if you are a ChunkType::Table or ChunkType::SparseTable. */
1953 assert(_sl.chunk_type == ChunkType::Table || _sl.chunk_type == ChunkType::SparseTable);
1954
1955 switch (_sl.action) {
1957 case SaveLoadAction::Load: {
1958 std::vector<SaveLoad> saveloads;
1959
1960 /* Build a key lookup mapping based on the available fields. */
1961 std::map<std::string, const SaveLoad *> key_lookup;
1962 for (auto &sld : slt) {
1963 if (!SlIsObjectValidInSavegame(sld)) continue;
1964
1965 /* Check that there is only one active SaveLoad for a given name. */
1966 assert(key_lookup.find(sld.name) == key_lookup.end());
1967 key_lookup[sld.name] = &sld;
1968 }
1969
1970 while (true) {
1971 SavegameFileType type{};
1973 if (type.IsEnd()) break;
1974
1975 std::string key;
1977
1978 auto sld_it = key_lookup.find(key);
1979 if (sld_it == key_lookup.end()) {
1980 /* SLA_LOADCHECK triggers this debug statement a lot and is perfectly normal. */
1981 Debug(Facility::Sl, _sl.action == SaveLoadAction::Load ? Severity::Warning : Severity::Debug2, "Field '{}' of type 0x{:02x} not found, skipping", key, type.storage);
1982
1983 std::shared_ptr<SaveLoadHandler> handler = nullptr;
1984 SaveLoadType saveload_type;
1985 switch (type.Type()) {
1987 saveload_type = SaveLoadType::String;
1988 break;
1989
1991 saveload_type = SaveLoadType::StructList;
1992 handler = std::make_shared<SlSkipHandler>();
1993 break;
1994
1995 default:
1997 break;
1998 }
1999
2000 /* We don't know this field, so read to nothing. */
2001 saveloads.emplace_back(std::move(key), saveload_type, VarType{type.Type(), VarMemType::Null}, 1, SaveLoadVersion::MinVersion, SaveLoadVersion::MaxVersion, nullptr, 0, std::move(handler));
2002 continue;
2003 }
2004
2005 /* Validate the type of the field. If it is changed, the
2006 * savegame should have been bumped so we know how to do the
2007 * conversion. If this error triggers, that clearly didn't
2008 * happen and this is a friendly poke to the developer to bump
2009 * the savegame version and add conversion code. */
2010 SavegameFileType correct_type = GetSavegameFileType(*sld_it->second);
2011 if (correct_type.storage != type.storage) {
2012 Debug(Facility::Sl, Severity::Error, "Field type for '{}' was expected to be 0x{:02x} but 0x{:02x} was found", key, correct_type.storage, type.storage);
2013 SlErrorCorrupt("Field type is different than expected");
2014 }
2015 saveloads.emplace_back(*sld_it->second);
2016 }
2017
2018 for (auto &sld : saveloads) {
2020 sld.handler->load_description = SlTableHeader(sld.handler->GetDescription());
2021 }
2022 }
2023
2024 return saveloads;
2025 }
2026
2027 case SaveLoadAction::Save: {
2028 /* Automatically calculate the length? */
2029 if (_sl.need_length != NeedLength::None) {
2031 if (_sl.need_length == NeedLength::CalcLength) break;
2032 }
2033
2034 for (auto &sld : slt) {
2035 if (!SlIsObjectValidInSavegame(sld)) continue;
2036 /* Make sure we are not storing empty keys. */
2037 assert(!sld.name.empty());
2038
2040 assert(!type.IsEnd());
2041
2043 SlStdString(const_cast<std::string *>(&sld.name), VarTypes::STR);
2044 }
2045
2046 /* Add an end-of-header marker. */
2047 SavegameFileType type{};
2049
2050 /* After the table, write down any sub-tables we might have. */
2051 for (auto &sld : slt) {
2052 if (!SlIsObjectValidInSavegame(sld)) continue;
2054 /* SlCalcTableHeader already looks in sub-lists, so avoid the length being added twice. */
2055 NeedLength old_need_length = _sl.need_length;
2056 _sl.need_length = NeedLength::None;
2057
2058 SlTableHeader(sld.handler->GetDescription());
2059
2060 _sl.need_length = old_need_length;
2061 }
2062 }
2063
2064 break;
2065 }
2066
2067 default: NOT_REACHED();
2068 }
2069
2070 return std::vector<SaveLoad>();
2071}
2072
2086std::vector<SaveLoad> SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
2087{
2088 assert(_sl.action == SaveLoadAction::Load || _sl.action == SaveLoadAction::LoadCheck);
2089 /* ChunkType::Table / ChunkType::SparseTable always have a header. */
2090 if (_sl.chunk_type == ChunkType::Table || _sl.chunk_type == ChunkType::SparseTable) return SlTableHeader(slt);
2091
2092 std::vector<SaveLoad> saveloads;
2093
2094 /* Build a key lookup mapping based on the available fields. */
2095 std::map<std::string_view, std::vector<const SaveLoad *>> key_lookup;
2096 for (auto &sld : slt) {
2097 /* All entries should have a name; otherwise the entry should just be removed. */
2098 assert(!sld.name.empty());
2099
2100 key_lookup[sld.name].push_back(&sld);
2101 }
2102
2103 for (auto &slc : slct) {
2104 if (slc.name.empty()) {
2105 /* In old savegames there can be data we no longer care for. We
2106 * skip this by simply reading the amount of bytes indicated and
2107 * send those to /dev/null. */
2108 saveloads.emplace_back("", SaveLoadType::Null, VarType{VarFileType::U8, VarMemType::Null}, slc.null_length, slc.version_from, slc.version_to, nullptr, 0, nullptr);
2109 } else {
2110 auto sld_it = key_lookup.find(slc.name);
2111 /* If this branch triggers, it means that an entry in the
2112 * SaveLoadCompat list is not mentioned in the SaveLoad list. Did
2113 * you rename a field in one and not in the other? */
2114 if (sld_it == key_lookup.end()) {
2115 /* This isn't an assert, as that leaves no information what
2116 * field was to blame. This way at least we have breadcrumbs. */
2117 Debug(Facility::Sl, Severity::Critical, "internal error: saveload compatibility field '{}' not found", slc.name);
2118 SlErrorCorrupt("Internal error with savegame compatibility");
2119 }
2120 for (auto &sld : sld_it->second) {
2121 saveloads.push_back(*sld);
2122 }
2123 }
2124 }
2125
2126 for (auto &sld : saveloads) {
2127 if (!SlIsObjectValidInSavegame(sld)) continue;
2129 sld.handler->load_description = SlCompatTableHeader(sld.handler->GetDescription(), sld.handler->GetCompatDescription());
2130 }
2131 }
2132
2133 return saveloads;
2134}
2135
2141{
2142 SlObject(nullptr, slt);
2143}
2144
2150void SlAutolength(AutolengthProc *proc, int arg)
2151{
2152 assert(_sl.action == SaveLoadAction::Save);
2153
2154 /* Tell it to calculate the length */
2155 _sl.need_length = NeedLength::CalcLength;
2156 _sl.obj_len = 0;
2157 proc(arg);
2158
2159 /* Setup length */
2160 _sl.need_length = NeedLength::WantLength;
2161 SlSetLength(_sl.obj_len);
2162
2163 size_t start_pos = _sl.dumper->GetSize();
2164 size_t expected_offs = start_pos + _sl.obj_len;
2165
2166 /* And write the stuff */
2167 proc(arg);
2168
2169 if (expected_offs != _sl.dumper->GetSize()) {
2170 SlErrorCorruptFmt("Invalid chunk size when writing autolength block, expected {}, got {}", _sl.obj_len, _sl.dumper->GetSize() - start_pos);
2171 }
2172}
2173
2174void ChunkHandler::LoadCheck(size_t len) const
2175{
2176 switch (_sl.chunk_type) {
2177 case ChunkType::Table:
2179 SlTableHeader({});
2180 [[fallthrough]];
2181 case ChunkType::Array:
2183 SlSkipArray();
2184 break;
2185 case ChunkType::Riff:
2186 SlSkipBytes(len);
2187 break;
2188 default:
2189 NOT_REACHED();
2190 }
2191}
2192
2197static void SlLoadChunk(const ChunkHandler &ch)
2198{
2199 uint8_t m = SlReadByte();
2200
2201 _sl.chunk_type = static_cast<ChunkType>(m & to_underlying(ChunkType::FileTypeMask));
2202 _sl.obj_len = 0;
2203 _sl.expect_table_header = (_sl.chunk_type == ChunkType::Table || _sl.chunk_type == ChunkType::SparseTable);
2204
2205 /* The header should always be at the start. Read the length; the
2206 * Load() should as first action process the header. */
2207 if (_sl.expect_table_header) {
2208 if (SlIterateArray() != INT32_MAX) SlErrorCorrupt("Table chunk without header");
2209 }
2210
2211 switch (_sl.chunk_type) {
2212 case ChunkType::Table:
2213 case ChunkType::Array:
2214 _sl.array_index = 0;
2215 ch.Load();
2216 if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
2217 break;
2220 ch.Load();
2221 if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
2222 break;
2223 case ChunkType::Riff: {
2224 /* Read length */
2225 size_t len = (SlReadByte() << 16) | ((m >> 4) << 24);
2226 len += SlReadUint16();
2227 _sl.obj_len = len;
2228 size_t start_pos = _sl.reader->GetSize();
2229 size_t endoffs = start_pos + len;
2230 ch.Load();
2231
2232 if (_sl.reader->GetSize() != endoffs) {
2233 SlErrorCorruptFmt("Invalid chunk size in RIFF in {} - expected {}, got {}", ch.GetName(), len, _sl.reader->GetSize() - start_pos);
2234 }
2235 break;
2236 }
2237 default:
2238 SlErrorCorrupt("Invalid chunk type");
2239 break;
2240 }
2241
2242 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2243}
2244
2250static void SlLoadCheckChunk(const ChunkHandler &ch)
2251{
2252 uint8_t m = SlReadByte();
2253
2254 _sl.chunk_type = static_cast<ChunkType>(m & to_underlying(ChunkType::FileTypeMask));
2255 _sl.obj_len = 0;
2256 _sl.expect_table_header = (_sl.chunk_type == ChunkType::Table || _sl.chunk_type == ChunkType::SparseTable);
2257
2258 /* The header should always be at the start. Read the length; the
2259 * LoadCheck() should as first action process the header. */
2260 if (_sl.expect_table_header) {
2261 if (SlIterateArray() != INT32_MAX) SlErrorCorrupt("Table chunk without header");
2262 }
2263
2264 switch (_sl.chunk_type) {
2265 case ChunkType::Table:
2266 case ChunkType::Array:
2267 _sl.array_index = 0;
2268 ch.LoadCheck();
2269 break;
2272 ch.LoadCheck();
2273 break;
2274 case ChunkType::Riff: {
2275 /* Read length */
2276 size_t len = (SlReadByte() << 16) | ((m >> 4) << 24);
2277 len += SlReadUint16();
2278 _sl.obj_len = len;
2279 size_t start_pos = _sl.reader->GetSize();
2280 size_t endoffs = start_pos + len;
2281 ch.LoadCheck(len);
2282
2283 if (_sl.reader->GetSize() != endoffs) {
2284 SlErrorCorruptFmt("Invalid chunk size in RIFF in {} - expected {}, got {}", ch.GetName(), len, _sl.reader->GetSize() - start_pos);
2285 }
2286 break;
2287 }
2288 default:
2289 SlErrorCorrupt("Invalid chunk type");
2290 break;
2291 }
2292
2293 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2294}
2295
2301static void SlSaveChunk(const ChunkHandler &ch)
2302{
2303 if (ch.type == ChunkType::ReadOnly) return;
2304
2305 for (uint8_t b : ch.id) SlWriteByte(b);
2306 Debug(Facility::Sl, Severity::Warning, "Saving chunk {}", ch.GetName());
2307
2308 _sl.chunk_type = ch.type;
2309 _sl.expect_table_header = (_sl.chunk_type == ChunkType::Table || _sl.chunk_type == ChunkType::SparseTable);
2310
2311 _sl.need_length = (_sl.expect_table_header || _sl.chunk_type == ChunkType::Riff) ? NeedLength::WantLength : NeedLength::None;
2312
2313 switch (_sl.chunk_type) {
2314 case ChunkType::Riff:
2315 ch.Save();
2316 break;
2317 case ChunkType::Table:
2318 case ChunkType::Array:
2319 _sl.last_array_index = 0;
2320 SlWriteByte(to_underlying(_sl.chunk_type));
2321 ch.Save();
2322 SlWriteArrayLength(0); // Terminate arrays
2323 break;
2326 SlWriteByte(to_underlying(_sl.chunk_type));
2327 ch.Save();
2328 SlWriteArrayLength(0); // Terminate arrays
2329 break;
2330 default: NOT_REACHED();
2331 }
2332
2333 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2334}
2335
2337static void SlSaveChunks()
2338{
2339 for (auto &ch : ChunkHandlers()) {
2340 SlSaveChunk(ch);
2341 }
2342
2343 /* Terminator */
2344 SlWriteUint32(0);
2345}
2346
2354{
2355 for (const ChunkHandler &ch : ChunkHandlers()) if (ch.id == id) return &ch;
2356 return nullptr;
2357}
2358
2360static void SlLoadChunks()
2361{
2362 for (ChunkId id = SlReadChunkId(); !id.Empty(); id = SlReadChunkId()) {
2363 Debug(Facility::Sl, Severity::Warning, "Loading chunk {}", id.AsString());
2364
2365 const ChunkHandler *ch = SlFindChunkHandler(id);
2366 if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2367 SlLoadChunk(*ch);
2368 }
2369}
2370
2373{
2374 for (ChunkId id = SlReadChunkId(); !id.Empty(); id = SlReadChunkId()) {
2375 Debug(Facility::Sl, Severity::Warning, "Loading chunk {}", id.AsString());
2376
2377 const ChunkHandler *ch = SlFindChunkHandler(id);
2378 if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2379 SlLoadCheckChunk(*ch);
2380 }
2381}
2382
2384static void SlFixPointers()
2385{
2386 _sl.action = SaveLoadAction::Ptrs;
2387
2388 for (const ChunkHandler &ch : ChunkHandlers()) {
2389 Debug(Facility::Sl, Severity::Notice, "Fixing pointers for {}", ch.GetName());
2390 ch.FixPointers();
2391 }
2392
2393 assert(_sl.action == SaveLoadAction::Ptrs);
2394}
2395
2396
2399 std::optional<FileHandle> file;
2400 long begin;
2401
2406 FileReader(FileHandle &&file) : LoadFilter(nullptr), file(std::move(file)), begin(ftell(*this->file))
2407 {
2408 }
2409
2411 ~FileReader() override
2412 {
2413 if (this->file.has_value()) {
2414 _game_session_stats.savegame_size = ftell(*this->file) - this->begin;
2415 }
2416 }
2417
2418 size_t Read(uint8_t *buf, size_t size) override
2419 {
2420 /* We're in the process of shutting down, i.e. in "failure" mode. */
2421 if (!this->file.has_value()) return 0;
2422
2423 return fread(buf, 1, size, *this->file);
2424 }
2425
2426 void Reset() override
2427 {
2428 clearerr(*this->file);
2429 if (fseek(*this->file, this->begin, SEEK_SET)) {
2430 Debug(Facility::Sl, Severity::Error, "Could not reset the file reading");
2431 }
2432 }
2433};
2434
2437 std::optional<FileHandle> file;
2438
2443 FileWriter(FileHandle &&file) : SaveFilter(nullptr), file(std::move(file))
2444 {
2445 }
2446
2448 ~FileWriter() override
2449 {
2450 this->Finish();
2451 }
2452
2453 void Write(const uint8_t *buf, size_t size) override
2454 {
2455 /* We're in the process of shutting down, i.e. in "failure" mode. */
2456 if (!this->file.has_value()) return;
2457
2458 if (fwrite(buf, 1, size, *this->file) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
2459 }
2460
2461 void Finish() override
2462 {
2463 if (this->file.has_value()) {
2464 _game_session_stats.savegame_size = ftell(*this->file);
2465 this->file.reset();
2466 }
2467 }
2468};
2469
2470/*******************************************
2471 ********** START OF LZO CODE **************
2472 *******************************************/
2473
2474#ifdef WITH_LZO
2475
2477static const uint LZO_BUFFER_SIZE = 8192;
2478
2485 LZOLoadFilter(std::shared_ptr<LoadFilter> chain) : LoadFilter(std::move(chain))
2486 {
2487 if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2488 }
2489
2490 size_t Read(uint8_t *buf, size_t ssize) override
2491 {
2492 assert(ssize >= LZO_BUFFER_SIZE);
2493
2494 /* Buffer size is from the LZO docs plus the chunk header size. */
2495 uint8_t out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32_t) * 2];
2496 uint32_t tmp[2];
2497 uint32_t size;
2498 lzo_uint len = ssize;
2499
2500 /* Read header*/
2501 if (this->chain->Read((uint8_t*)tmp, sizeof(tmp)) != sizeof(tmp)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed");
2502
2503 /* Check if size is bad */
2504 ((uint32_t*)out)[0] = size = tmp[1];
2505
2507 tmp[0] = TO_BE32(tmp[0]);
2508 size = TO_BE32(size);
2509 }
2510
2511 if (size >= sizeof(out)) SlErrorCorrupt("Inconsistent size");
2512
2513 /* Read block */
2514 if (this->chain->Read(out + sizeof(uint32_t), size) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2515
2516 /* Verify checksum */
2517 if (tmp[0] != lzo_adler32(0, out, size + sizeof(uint32_t))) SlErrorCorrupt("Bad checksum");
2518
2519 /* Decompress */
2520 int ret = lzo1x_decompress_safe(out + sizeof(uint32_t) * 1, size, buf, &len, nullptr);
2521 if (ret != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2522 return len;
2523 }
2524};
2525
2532 LZOSaveFilter(std::shared_ptr<SaveFilter> chain, uint8_t) : SaveFilter(std::move(chain))
2533 {
2534 if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2535 }
2536
2537 void Write(const uint8_t *buf, size_t size) override
2538 {
2539 const lzo_bytep in = buf;
2540 /* Buffer size is from the LZO docs plus the chunk header size. */
2541 uint8_t out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32_t) * 2];
2542 uint8_t wrkmem[LZO1X_1_MEM_COMPRESS];
2543 lzo_uint outlen;
2544
2545 do {
2546 /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2547 lzo_uint len = size > LZO_BUFFER_SIZE ? LZO_BUFFER_SIZE : static_cast<lzo_uint>(size);
2548 lzo1x_1_compress(in, len, out + sizeof(uint32_t) * 2, &outlen, wrkmem);
2549 ((uint32_t*)out)[1] = TO_BE32(static_cast<uint32_t>(outlen));
2550 ((uint32_t*)out)[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32_t), outlen + sizeof(uint32_t)));
2551 this->chain->Write(out, outlen + sizeof(uint32_t) * 2);
2552
2553 /* Move to next data chunk. */
2554 size -= len;
2555 in += len;
2556 } while (size > 0);
2557 }
2558};
2559
2560#endif /* WITH_LZO */
2561
2562/*********************************************
2563 ******** START OF NOCOMP CODE (uncompressed)*
2564 *********************************************/
2565
2572 NoCompLoadFilter(std::shared_ptr<LoadFilter> chain) : LoadFilter(std::move(chain))
2573 {
2574 }
2575
2576 size_t Read(uint8_t *buf, size_t size) override
2577 {
2578 return this->chain->Read(buf, size);
2579 }
2580};
2581
2588 NoCompSaveFilter(std::shared_ptr<SaveFilter> chain, uint8_t) : SaveFilter(std::move(chain))
2589 {
2590 }
2591
2592 void Write(const uint8_t *buf, size_t size) override
2593 {
2594 this->chain->Write(buf, size);
2595 }
2596};
2597
2598/********************************************
2599 ********** START OF ZLIB CODE **************
2600 ********************************************/
2601
2602#if defined(WITH_ZLIB)
2603
2606 z_stream z{};
2608
2613 ZlibLoadFilter(std::shared_ptr<LoadFilter> chain) : LoadFilter(std::move(chain))
2614 {
2615 if (inflateInit(&this->z) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2616 }
2617
2620 {
2621 inflateEnd(&this->z);
2622 }
2623
2624 size_t Read(uint8_t *buf, size_t size) override
2625 {
2626 this->z.next_out = buf;
2627 this->z.avail_out = static_cast<uint>(size);
2628
2629 do {
2630 /* read more bytes from the file? */
2631 if (this->z.avail_in == 0) {
2632 this->z.next_in = this->fread_buf;
2633 this->z.avail_in = static_cast<uint>(this->chain->Read(this->fread_buf, sizeof(this->fread_buf)));
2634 }
2635
2636 /* inflate the data */
2637 int r = inflate(&this->z, 0);
2638 if (r == Z_STREAM_END) break;
2639
2640 if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "inflate() failed");
2641 } while (this->z.avail_out != 0);
2642
2643 return size - this->z.avail_out;
2644 }
2645};
2646
2649 z_stream z{};
2651
2657 ZlibSaveFilter(std::shared_ptr<SaveFilter> chain, uint8_t compression_level) : SaveFilter(std::move(chain))
2658 {
2659 if (deflateInit(&this->z, compression_level) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2660 }
2661
2664 {
2665 deflateEnd(&this->z);
2666 }
2667
2674 void WriteLoop(const uint8_t *p, size_t len, int mode)
2675 {
2676 uint n;
2677 this->z.next_in = const_cast<uint8_t *>(p); // zlib does not modify the data, but is non-const for legacy reasons
2678 this->z.avail_in = static_cast<uInt>(len);
2679 do {
2680 this->z.next_out = this->fwrite_buf;
2681 this->z.avail_out = sizeof(this->fwrite_buf);
2682
2690 int r = deflate(&this->z, mode);
2691
2692 /* bytes were emitted? */
2693 if ((n = sizeof(this->fwrite_buf) - this->z.avail_out) != 0) {
2694 this->chain->Write(this->fwrite_buf, n);
2695 }
2696 if (r == Z_STREAM_END) break;
2697
2698 if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "zlib returned error code");
2699 } while (this->z.avail_in || !this->z.avail_out);
2700 }
2701
2702 void Write(const uint8_t *buf, size_t size) override
2703 {
2704 this->WriteLoop(buf, size, 0);
2705 }
2706
2707 void Finish() override
2708 {
2709 this->WriteLoop(nullptr, 0, Z_FINISH);
2710 this->chain->Finish();
2711 }
2712};
2713
2714#endif /* WITH_ZLIB */
2715
2716/********************************************
2717 ********** START OF LZMA CODE **************
2718 ********************************************/
2719
2720#if defined(WITH_LIBLZMA)
2721
2728static const lzma_stream _lzma_init = LZMA_STREAM_INIT;
2729
2732 lzma_stream lzma;
2734
2739 LZMALoadFilter(std::shared_ptr<LoadFilter> chain) : LoadFilter(std::move(chain)), lzma(_lzma_init)
2740 {
2741 /* Allow saves up to 256 MB uncompressed */
2742 if (lzma_auto_decoder(&this->lzma, 1 << 28, 0) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2743 }
2744
2747 {
2748 lzma_end(&this->lzma);
2749 }
2750
2751 size_t Read(uint8_t *buf, size_t size) override
2752 {
2753 this->lzma.next_out = buf;
2754 this->lzma.avail_out = size;
2755
2756 do {
2757 /* read more bytes from the file? */
2758 if (this->lzma.avail_in == 0) {
2759 this->lzma.next_in = this->fread_buf;
2760 this->lzma.avail_in = this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2761 }
2762
2763 /* inflate the data */
2764 lzma_ret r = lzma_code(&this->lzma, LZMA_RUN);
2765 if (r == LZMA_STREAM_END) break;
2766 if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2767 } while (this->lzma.avail_out != 0);
2768
2769 return size - this->lzma.avail_out;
2770 }
2771};
2772
2775 lzma_stream lzma;
2777
2783 LZMASaveFilter(std::shared_ptr<SaveFilter> chain, uint8_t compression_level) : SaveFilter(std::move(chain)), lzma(_lzma_init)
2784 {
2785 if (lzma_easy_encoder(&this->lzma, compression_level, LZMA_CHECK_CRC32) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2786 }
2787
2790 {
2791 lzma_end(&this->lzma);
2792 }
2793
2800 void WriteLoop(const uint8_t *p, size_t len, lzma_action action)
2801 {
2802 size_t n;
2803 this->lzma.next_in = p;
2804 this->lzma.avail_in = len;
2805 do {
2806 this->lzma.next_out = this->fwrite_buf;
2807 this->lzma.avail_out = sizeof(this->fwrite_buf);
2808
2809 lzma_ret r = lzma_code(&this->lzma, action);
2810
2811 /* bytes were emitted? */
2812 if ((n = sizeof(this->fwrite_buf) - this->lzma.avail_out) != 0) {
2813 this->chain->Write(this->fwrite_buf, n);
2814 }
2815 if (r == LZMA_STREAM_END) break;
2816 if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2817 } while (this->lzma.avail_in || !this->lzma.avail_out);
2818 }
2819
2820 void Write(const uint8_t *buf, size_t size) override
2821 {
2822 this->WriteLoop(buf, size, LZMA_RUN);
2823 }
2824
2825 void Finish() override
2826 {
2827 this->WriteLoop(nullptr, 0, LZMA_FINISH);
2828 this->chain->Finish();
2829 }
2830};
2831
2832#endif /* WITH_LIBLZMA */
2833
2834/*******************************************
2835 ************* END OF CODE *****************
2836 *******************************************/
2837
2840
2843 std::shared_ptr<LoadFilter> (*init_load)(std::shared_ptr<LoadFilter> chain);
2844 std::shared_ptr<SaveFilter> (*init_write)(std::shared_ptr<SaveFilter> chain, uint8_t compression);
2845
2846 std::string_view name;
2848
2852};
2853
2858
2861#if defined(WITH_LZO)
2862 /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2864#else
2865 {nullptr, nullptr, "lzo", SAVEGAME_TAG_LZO, 0, 0, 0},
2866#endif
2867 /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2869#if defined(WITH_ZLIB)
2870 /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2871 * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2872 * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2874#else
2875 {nullptr, nullptr, "zlib", SAVEGAME_TAG_ZLIB, 0, 0, 0},
2876#endif
2877#if defined(WITH_LIBLZMA)
2878 /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2879 * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2880 * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2881 * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2882 * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2884#else
2885 {nullptr, nullptr, "lzma", SAVEGAME_TAG_LZMA, 0, 0, 0},
2886#endif
2887};
2888
2895static std::pair<const SaveLoadFormat &, uint8_t> GetSavegameFormat(std::string_view full_name)
2896{
2897 /* Find default savegame format, the highest one with which files can be written. */
2898 auto it = std::find_if(std::rbegin(_saveload_formats), std::rend(_saveload_formats), [](const auto &slf) { return slf.init_write != nullptr; });
2899 if (it == std::rend(_saveload_formats)) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "no writeable savegame formats");
2900
2901 const SaveLoadFormat &def = *it;
2902
2903 if (!full_name.empty()) {
2904 /* Get the ":..." of the compression level out of the way */
2905 size_t separator = full_name.find(':');
2906 bool has_comp_level = separator != std::string::npos;
2907 std::string_view name = has_comp_level ? full_name.substr(0, separator) : full_name;
2908
2909 for (const auto &slf : _saveload_formats) {
2910 if (slf.init_write != nullptr && name == slf.name) {
2911 if (has_comp_level) {
2912 auto complevel = full_name.substr(separator + 1);
2913
2914 /* Get the level and determine whether all went fine. */
2915 auto level = ParseInteger<uint8_t>(complevel);
2916 if (!level.has_value() || *level != Clamp(*level, slf.min_compression, slf.max_compression)) {
2918 GetEncodedString(STR_CONFIG_ERROR),
2919 GetEncodedString(STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL, complevel),
2921 } else {
2922 return {slf, *level};
2923 }
2924 }
2925 return {slf, slf.default_compression};
2926 }
2927 }
2928
2930 GetEncodedString(STR_CONFIG_ERROR),
2931 GetEncodedString(STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM, name, def.name),
2933 }
2934 return {def, def.default_compression};
2935}
2936
2937/* actual loader/saver function */
2938void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
2939extern bool AfterLoadGame();
2940extern bool LoadOldSaveGame(std::string_view file);
2941
2947static void ResetSettings()
2948{
2949 for (auto &desc : GetSaveLoadSettingTable()) {
2950 const SettingDesc *sd = GetSettingDesc(desc);
2951 if (sd->flags.Test(SettingFlag::NotInSave)) continue;
2953
2955 }
2956}
2957
2962{
2965 ResetTempEngineData();
2966 ClearRailTypeLabelList();
2967 ClearRoadTypeLabelList();
2968 ResetOldWaypoints();
2969 ResetSettings();
2970}
2971
2975static inline void ClearSaveLoadState()
2976{
2977 _sl.dumper = nullptr;
2978 _sl.sf = nullptr;
2979 _sl.reader = nullptr;
2980 _sl.lf = nullptr;
2981}
2982
2984static void SaveFileStart()
2985{
2986 SetMouseCursorBusy(true);
2987
2988 InvalidateWindowData(WindowClass::Statusbar, 0, SBI_SAVELOAD_START);
2989 _sl.saveinprogress = true;
2990}
2991
2993static void SaveFileDone()
2994{
2995 SetMouseCursorBusy(false);
2996
2997 InvalidateWindowData(WindowClass::Statusbar, 0, SBI_SAVELOAD_FINISH);
2998 _sl.saveinprogress = false;
2999
3000#ifdef __EMSCRIPTEN__
3001 EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
3002#endif
3003}
3004
3010{
3011 _sl.error_str = str;
3012}
3013
3019{
3020 return GetEncodedString(_sl.action == SaveLoadAction::Save ? STR_ERROR_GAME_SAVE_FAILED : STR_ERROR_GAME_LOAD_FAILED);
3021}
3022
3028{
3029 return GetEncodedString(_sl.error_str, _sl.extra_msg);
3030}
3031
3038
3045static SaveLoadResult SaveFileToDisk(bool threaded)
3046{
3047 try {
3048 auto [fmt, compression] = GetSavegameFormat(_savegame_format);
3049
3050 /* We have written our stuff to memory, now write it to file! */
3051 _sl.sf->Write(fmt.tag.data(), fmt.tag.size());
3052
3053 uint32_t version = TO_BE32(to_underlying(SAVEGAME_VERSION) << 16);
3054 _sl.sf->Write(reinterpret_cast<uint8_t *>(&version), sizeof(version));
3055
3056 _sl.sf = fmt.init_write(_sl.sf, compression);
3057 _sl.dumper->Flush(_sl.sf);
3058
3060
3061 if (threaded) SetAsyncSaveFinish(SaveFileDone);
3062
3063 return SaveLoadResult::Ok;
3064 } catch (...) {
3066
3068
3069 /* We don't want to shout when saving is just
3070 * cancelled due to a client disconnecting. */
3071 if (_sl.error_str != STR_NETWORK_ERROR_LOSTCONNECTION) {
3072 Debug(Facility::Sl, Severity::Critical, "{} {}", GetSaveLoadErrorType().GetDecodedString(), GetSaveLoadErrorMessage().GetDecodedString());
3073 asfp = SaveFileError;
3074 }
3075
3076 if (threaded) {
3077 SetAsyncSaveFinish(asfp);
3078 } else {
3079 asfp();
3080 }
3081 return SaveLoadResult::Error;
3082 }
3083}
3084
3085void WaitTillSaved()
3086{
3087 if (!_save_thread.joinable()) return;
3088
3089 _save_thread.join();
3090
3091 /* Make sure every other state is handled properly as well. */
3093}
3094
3103static SaveLoadResult DoSave(std::shared_ptr<SaveFilter> writer, bool threaded)
3104{
3105 assert(!_sl.saveinprogress);
3106
3107 _sl.dumper = std::make_unique<MemoryDumper>();
3108 _sl.sf = std::move(writer);
3109
3111
3112 SaveViewportBeforeSaveGame();
3113 SlSaveChunks();
3114
3115 SaveFileStart();
3116
3117 if (!threaded || !StartNewThread(&_save_thread, "ottd:savegame", &SaveFileToDisk, true)) {
3118 if (threaded) Debug(Facility::Sl, Severity::Error, "Cannot create savegame thread, reverting to single-threaded mode...");
3119
3120 SaveLoadResult result = SaveFileToDisk(false);
3121 SaveFileDone();
3122
3123 return result;
3124 }
3125
3126 return SaveLoadResult::Ok;
3127}
3128
3135SaveLoadResult SaveWithFilter(std::shared_ptr<SaveFilter> writer, bool threaded)
3136{
3137 try {
3138 _sl.action = SaveLoadAction::Save;
3139 return DoSave(std::move(writer), threaded);
3140 } catch (...) {
3142 return SaveLoadResult::Error;
3143 }
3144}
3145
3154static const SaveLoadFormat *DetermineSaveLoadFormat(SaveLoadFormatTag tag, uint32_t raw_version)
3155{
3156 auto fmt = std::ranges::find(_saveload_formats, tag, &SaveLoadFormat::tag);
3157 if (fmt != std::end(_saveload_formats)) {
3158 /* Check version number */
3159 _sl_version = (SaveLoadVersion)(TO_BE32(raw_version) >> 16);
3160 /* Minor is not used anymore from version 18.0, but it is still needed
3161 * in versions before that (4 cases) which can't be removed easy.
3162 * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
3163 _sl_minor_version = (TO_BE32(raw_version) >> 8) & 0xFF;
3164
3165 Debug(Facility::Sl, Severity::Error, "Loading savegame version {}", _sl_version);
3166
3167 /* Is the version higher than the current? */
3168 if (_sl_version > SAVEGAME_VERSION) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME);
3170 return fmt;
3171 }
3172
3173 Debug(Facility::Sl, Severity::Critical, "Unknown savegame type, trying to load it as the buggy format");
3174 _sl.lf->Reset();
3177
3178 /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
3179 fmt = std::ranges::find(_saveload_formats, SAVEGAME_TAG_LZO, &SaveLoadFormat::tag);
3180 if (fmt == std::end(_saveload_formats)) {
3181 /* Who removed the LZO savegame format definition? When built without LZO support,
3182 * the formats must still list it just without a method to read the file.
3183 * The caller of this function has to check for the existence of load function. */
3184 NOT_REACHED();
3185 }
3186 return fmt;
3187}
3188
3195static SaveLoadResult DoLoad(std::shared_ptr<LoadFilter> reader, bool load_check)
3196{
3197 _sl.lf = std::move(reader);
3198
3199 if (load_check) {
3200 /* Clear previous check data */
3201 _load_check_data.Clear();
3202 /* Mark SL_LOAD_CHECK as supported for this savegame. */
3203 _load_check_data.checkable = true;
3204 }
3205
3206 SaveLoadFormatTag tag{};
3207 if (_sl.lf->Read(tag.data(), tag.size()) != tag.size()) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3208
3209 uint32_t version;
3210 if (_sl.lf->Read(reinterpret_cast<uint8_t*>(&version), sizeof(version)) != sizeof(version)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3211
3212 /* see if we have any loader for this type. */
3213 const SaveLoadFormat *fmt = DetermineSaveLoadFormat(tag, version);
3214
3215 /* loader for this savegame type is not implemented? */
3216 if (fmt->init_load == nullptr) {
3217 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, fmt::format("Loader for '{}' is not available.", fmt->name));
3218 }
3219
3220 _sl.lf = fmt->init_load(_sl.lf);
3221 _sl.reader = std::make_unique<ReadBuffer>(_sl.lf);
3222 _next_offs = 0;
3223
3224 if (!load_check) {
3226
3227 /* Old maps were hardcoded to 256x256 and thus did not contain
3228 * any mapsize information. Pre-initialize to 256x256 to not to
3229 * confuse old games */
3230 InitializeGame(256, 256, true, true);
3231
3232 _gamelog.Reset();
3233
3235 /*
3236 * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
3237 * shared savegame version 4. Anything before that 'obviously'
3238 * does not have any NewGRFs. Between the introduction and
3239 * savegame version 41 (just before 0.5) the NewGRF settings
3240 * were not stored in the savegame and they were loaded by
3241 * using the settings from the main menu.
3242 * So, to recap:
3243 * - savegame version < 4: do not load any NewGRFs.
3244 * - savegame version >= 41: load NewGRFs from savegame, which is
3245 * already done at this stage by
3246 * overwriting the main menu settings.
3247 * - other savegame versions: use main menu settings.
3248 *
3249 * This means that users *can* crash savegame version 4..40
3250 * savegames if they set incompatible NewGRFs in the main menu,
3251 * but can't crash anymore for savegame version < 4 savegames.
3252 *
3253 * Note: this is done here because AfterLoadGame is also called
3254 * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
3255 */
3257 }
3258 }
3259
3260 if (load_check) {
3261 /* Load chunks into _load_check_data.
3262 * No pools are loaded. References are not possible, and thus do not need resolving. */
3264 } else {
3265 /* Load chunks and resolve references */
3266 SlLoadChunks();
3267 SlFixPointers();
3268 }
3269
3271
3273
3274 if (load_check) {
3275 /* The only part from AfterLoadGame() we need */
3276 _load_check_data.grf_compatibility = IsGoodGRFConfigList(_load_check_data.grfconfig);
3277 } else {
3278 _gamelog.StartAction(GamelogActionType::Load);
3279
3280 /* After loading fix up savegame for any internal changes that
3281 * might have occurred since then. If it fails, load back the old game. */
3282 if (!AfterLoadGame()) {
3283 _gamelog.StopAction();
3285 }
3286
3287 _gamelog.StopAction();
3288 }
3289
3290 return SaveLoadResult::Ok;
3291}
3292
3298SaveLoadResult LoadWithFilter(std::shared_ptr<LoadFilter> reader)
3299{
3300 try {
3301 _sl.action = SaveLoadAction::Load;
3302 return DoLoad(std::move(reader), false);
3303 } catch (...) {
3306 }
3307}
3308
3319SaveLoadResult SaveOrLoad(std::string_view filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
3320{
3321 /* An instance of saving is already active, so don't go saving again */
3322 if (_sl.saveinprogress && fop == SaveLoadOperation::Save && dft == DetailedFileType::GameFile && threaded) {
3323 /* if not an autosave, but a user action, show error message */
3324 if (!_do_autosave) ShowErrorMessage(GetEncodedString(STR_ERROR_SAVE_STILL_IN_PROGRESS), {}, WarningLevel::Error);
3325 return SaveLoadResult::Ok;
3326 }
3327 WaitTillSaved();
3328
3329 try {
3330 /* Load a TTDLX or TTDPatch game */
3333
3334 InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
3335
3336 /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
3337 * and if so a new NewGRF list will be made in LoadOldSaveGame.
3338 * Note: this is done here because AfterLoadGame is also called
3339 * for OTTD savegames which have their own NewGRF logic. */
3341 _gamelog.Reset();
3342 if (!LoadOldSaveGame(filename)) return SaveLoadResult::ReInit;
3345 _gamelog.StartAction(GamelogActionType::Load);
3346 if (!AfterLoadGame()) {
3347 _gamelog.StopAction();
3349 }
3350 _gamelog.StopAction();
3351 return SaveLoadResult::Ok;
3352 }
3353
3354 assert(dft == DetailedFileType::GameFile);
3355 switch (fop) {
3358 break;
3359
3361 _sl.action = SaveLoadAction::Load;
3362 break;
3363
3365 _sl.action = SaveLoadAction::Save;
3366 break;
3367
3368 default: NOT_REACHED();
3369 }
3370
3371 auto fh = (fop == SaveLoadOperation::Save) ? FioFOpenFile(filename, "wb", sb) : FioFOpenFile(filename, "rb", sb);
3372
3373 /* Make it a little easier to load savegames from the console */
3374 if (!fh.has_value() && fop != SaveLoadOperation::Save) fh = FioFOpenFile(filename, "rb", Subdirectory::Save);
3375 if (!fh.has_value() && fop != SaveLoadOperation::Save) fh = FioFOpenFile(filename, "rb", Subdirectory::Base);
3376 if (!fh.has_value() && fop != SaveLoadOperation::Save) fh = FioFOpenFile(filename, "rb", Subdirectory::Scenario);
3377
3378 if (!fh.has_value()) {
3379 SlError(fop == SaveLoadOperation::Save ? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE : STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3380 }
3381
3382 if (fop == SaveLoadOperation::Save) { // SAVE game
3384 if (!_settings_client.gui.threaded_saves) threaded = false;
3385
3386 return DoSave(std::make_shared<FileWriter>(std::move(*fh)), threaded);
3387 }
3388
3389 /* LOAD game */
3390 assert(fop == SaveLoadOperation::Load || fop == SaveLoadOperation::Check);
3391 Debug(Facility::Desync, Severity::Error, "load: {}", filename);
3392 return DoLoad(std::make_shared<FileReader>(std::move(*fh)), fop == SaveLoadOperation::Check);
3393 } catch (...) {
3394 /* This code may be executed both for old and new save games. */
3396
3397 if (fop != SaveLoadOperation::Check) Debug(Facility::Sl, Severity::Critical, "{} {}", GetSaveLoadErrorType().GetDecodedString(), GetSaveLoadErrorMessage().GetDecodedString());
3398
3399 /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3401 }
3402}
3403
3409{
3410 std::string filename;
3411
3412 if (_settings_client.gui.keep_all_autosave) {
3413 filename = GenerateDefaultSaveName() + counter.Extension();
3414 } else {
3415 filename = counter.Filename();
3416 }
3417
3418 Debug(Facility::Sl, Severity::Warning, "Autosaving to '{}'", filename);
3420 ShowErrorMessage(GetEncodedString(STR_ERROR_AUTOSAVE_FAILED), {}, WarningLevel::Error);
3421 }
3422}
3423
3424
3430
3436{
3437 /* Check if we have a name for this map, which is the name of the first
3438 * available company. When there's no company available we'll use
3439 * 'Spectator' as "company" name. */
3440 CompanyID cid = _local_company;
3441 if (!Company::IsValidID(cid)) {
3442 for (const Company *c : Company::Iterate()) {
3443 cid = c->index;
3444 break;
3445 }
3446 }
3447
3448 std::array<StringParameter, 4> params{};
3449 auto it = params.begin();
3450 *it++ = cid;
3451
3452 /* We show the current game time differently depending on the timekeeping units used by this game. */
3454 /* Insert time played. */
3455 const auto play_time = TimerGameTick::counter / Ticks::TICKS_PER_SECOND;
3456 *it++ = STR_SAVEGAME_DURATION_REALTIME;
3457 *it++ = play_time / 60 / 60;
3458 *it++ = (play_time / 60) % 60;
3459 } else {
3460 /* Insert current date */
3461 switch (_settings_client.gui.date_format_in_default_names) {
3462 case 0: *it++ = STR_JUST_DATE_LONG; break;
3463 case 1: *it++ = STR_JUST_DATE_TINY; break;
3464 case 2: *it++ = STR_JUST_DATE_ISO; break;
3465 default: NOT_REACHED();
3466 }
3467 *it++ = TimerGameEconomy::date;
3468 }
3469
3470 /* Get the correct string (special string for when there's not company) */
3471 std::string filename = GetStringWithArgs(!Company::IsValidID(cid) ? STR_SAVEGAME_NAME_SPECTATOR : STR_SAVEGAME_NAME_DEFAULT, params);
3472 SanitizeFilename(filename);
3473 return filename;
3474}
3475
3482{
3485 this->ftype = FIOS_TYPE_INVALID;
3486 return;
3487 }
3488
3489 this->file_op = fop;
3490 this->ftype = ft;
3491}
3492
3498{
3499 this->SetMode(item.type);
3500 this->name = item.name;
3501 this->title = item.title;
3502}
3503
3505{
3506 assert(this->load_description.has_value());
3507 return *this->load_description;
3508}
OldEngineRenewPool _old_engine_renew_saveload_pool
Temporary storage for conversion from old engine renew pool.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr enable_if_t< is_integral_v< T >, T > byteswap(T x) noexcept
Custom implementation of std::byteswap; remove once we build with C++23.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
void PutUtf8(char32_t c)
Append UTF-8 char.
void Put(std::string_view str)
Append string.
void PutIntegerBase(T value, int base)
Append integer 'value' in given number 'base'.
Container for an encoded string, created by GetEncodedString.
Class for calculation jobs to be run on link graphs.
A connected component of a link graph.
Definition linkgraph.h:35
Handler for saving/loading an object to/from disk.
Definition saveload.h:521
std::optional< std::vector< SaveLoad > > load_description
Description derived from savegame being loaded.
Definition saveload.h:523
SaveLoadTable GetLoadDescription() const
Get the description for how to load the chunk.
Handler that is assigned when there is a struct read in the savegame which is not known to the code.
SaveLoadCompatTable GetCompatDescription() const override
Get the pre-header description of the fields in the savegame.
SaveLoadTable GetDescription() const override
Get the description of the fields in the savegame.
void LoadCheck(void *object) const override
Similar to load, but used only to validate savegames.
void Load(void *object) const override
Load the object from disk.
void Save(void *) const override
Save the object to disk.
Template class to help with list-like types.
static size_t SlCalcLen(const void *storage, VarType conv, SaveLoadType cmd=SaveLoadType::Variable)
Internal templated helper to return the size in bytes of a list-like type.
static void SlSaveLoad(void *storage, VarType conv, SaveLoadType cmd=SaveLoadType::Variable)
Internal templated helper to save/load a list-like type.
Compose data into a growing std::string.
Parse data from a string / buffer.
std::optional< T > TryReadIntegerBase(int base, bool clamp=false)
Try to read and parse an integer in number 'base', and then advance the reader.
@ READ_ONE_SEPARATOR
Read one separator, and include it in the result.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
std::optional< char32_t > TryReadUtf8()
Try to read a UTF-8 character, and then advance reader.
T ReadIntegerBase(int base, T def=0, bool clamp=false)
Read and parse an integer in number 'base', and advance the reader.
bool ReadUtf8If(char32_t c)
Check whether the next UTF-8 char matches 'c', and skip it.
std::string_view ReadUntilUtf8(char32_t c, SeparatorUsage sep)
Read data until the first occurrence of UTF-8 char 'c', and advance reader.
static constexpr TimerGameTick::Ticks TICKS_PER_SECOND
Estimation of how many ticks fit in a single second.
static Date date
Current date in days (day counter).
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static DateFract date_fract
Fractional part of the day.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Functions related to companies.
Control codes that are embedded in the translation strings.
@ SCC_ENCODED
Encoded string marker and sub-string parameter.
@ SCC_ENCODED_NUMERIC
Encoded numeric parameter.
@ SCC_ENCODED_STRING
Encoded string parameter.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Desync
Desync message facility.
Definition debug_type.h:41
@ Sl
Saveload message facility.
Definition debug_type.h:39
@ Warning
Warning, wrong but okay if you don't know.
Definition debug_type.h:17
@ Notice
Notice.
Definition debug_type.h:18
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Debug2
Debug #2 - Low level debug messages.
Definition debug_type.h:21
@ Error
Error, but we are recovering.
Definition debug_type.h:16
Function to handling different endian machines.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
Functions related to errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
Definition error.h:25
@ Error
Errors (eg. saving/loading failed).
Definition error.h:24
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
void SanitizeFilename(std::string &filename)
Sanitizes a filename, i.e.
Definition fileio.cpp:1056
std::optional< FileHandle > FioFOpenFile(std::string_view filename, std::string_view mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition fileio.cpp:248
Functions for standard in/out file operations.
SaveLoadOperation
Operation performed on the file.
Definition fileio_type.h:51
@ Check
Load file for checking and/or preview.
Definition fileio_type.h:52
@ Invalid
Unknown file operation.
Definition fileio_type.h:56
@ Save
File is being saved.
Definition fileio_type.h:54
@ Load
File is being loaded.
Definition fileio_type.h:53
DetailedFileType
Kinds of files in each AbstractFileType.
Definition fileio_type.h:27
@ OldGameFile
Old save game or scenario file.
Definition fileio_type.h:29
@ GameFile
Save game or scenario file.
Definition fileio_type.h:30
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition fileio_type.h:87
@ Base
Base directory for all subdirectories.
Definition fileio_type.h:88
@ Autosave
Subdirectory of save for autosaves.
Definition fileio_type.h:90
@ Scenario
Base directory for all scenarios.
Definition fileio_type.h:91
@ Save
Base directory for all savegames.
Definition fileio_type.h:89
@ Invalid
Invalid or unknown file type.
Definition fileio_type.h:23
@ None
nothing to do
Definition fileio_type.h:17
Declarations for savegames operations.
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition fios_gui.cpp:42
fluid_settings_t * settings
FluidSynth settings handle.
uint32_t _ttdp_version
version of TTDP savegame (if applicable)
Definition saveload.cpp:82
SaveLoadVersion _sl_version
the major savegame version identifier
Definition saveload.cpp:83
uint8_t _sl_minor_version
the minor savegame version, DO NOT USE!
Definition saveload.cpp:84
Gamelog _gamelog
Gamelog instance.
Definition gamelog.cpp:30
SavegameType _savegame_type
type of savegame we are loading
Definition saveload.cpp:79
const SaveLoadVersion SAVEGAME_VERSION
current savegame version
Functions to be called to log fundamental changes to the game.
@ Load
Game loaded.
Definition gamelog.h:20
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
Definition gfx.cpp:1689
GameSessionStats _game_session_stats
Statistics about the current session.
Definition gfx.cpp:47
Declaration of link graph classes used for cargo distribution.
Declaration of link graph job classes used for cargo distribution.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
bool _networking
are we in networking mode?
Definition network.cpp:63
bool _network_server
network-server is active
Definition network.cpp:64
Basic functions/variables used all over the place.
GRFConfigList _grfconfig
First item in list of current GRF set up.
GRFListCompatibility IsGoodGRFConfigList(GRFConfigList &grfconfig)
Check if all GRFs in the GRF config from a savegame can be loaded.
void ClearGRFConfigList(GRFConfigList &config)
Clear a GRF Config list, freeing all nodes.
NewGRF handling of rail types.
NewGRF handling of road types.
uint8_t ReadByte(LoadgameState &ls)
Reads a byte from the buffer and decompress if needed.
Definition oldloader.cpp:86
OldOrderPool _old_order_saveload_pool
Temporary storage for conversion from old order pool.
Definition order_sl.cpp:110
Base class for roadstops.
A number of safeguards to prevent using unsafe methods.
static void SlRefVector(void *vector, VarType conv)
Save/Load a vector.
static const uint LZO_BUFFER_SIZE
Buffer size for the LZO compressor.
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition saveload.cpp:341
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition saveload.cpp:396
void FixSCCEncodedNegative(std::string &str)
Scan the string for SCC_ENCODED_NUMERIC with negative values, and reencode them as uint64_t.
static const lzma_stream _lzma_init
Have a copy of an initialised LZMA stream.
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 retu...
static SaveLoadResult DoSave(std::shared_ptr< SaveFilter > writer, bool threaded)
Actually perform the saving of the savegame.
static const SaveLoadFormat _saveload_formats[]
The different saveload formats known/understood by OpenTTD.
std::string _savegame_format
how to compress savegames
Definition saveload.cpp:85
static void SaveFileDone()
Update the gui accordingly when saving is done and release locks on saveload.
SaveLoadVersion _sl_version
the major savegame version identifier
Definition saveload.cpp:83
static SavegameFileType GetSavegameFileType(const SaveLoad &sld)
Return the type as saved/loaded inside the savegame.
Definition saveload.cpp:639
SaveLoadResult SaveOrLoad(std::string_view filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
static uint32_t ReferenceToInt(const void *obj, SLRefType rt)
Pointers cannot be saved to a savegame, so this functions gets the index of the item,...
static const std::vector< ChunkHandlerRef > & ChunkHandlers()
Definition saveload.cpp:222
static size_t SlCalcRefVectorLen(const void *vector, VarType conv)
Return the size in bytes of a vector.
static void ResetSaveloadData()
Clear temporary data that is passed between various saveload phases.
static void SlWriteSimpleGamma(size_t i)
Write the header descriptor of an object or an array.
Definition saveload.cpp:525
static size_t SlCalcTableHeader(const SaveLoadTable &slt)
Calculate the size of the table header.
static void ClearSaveLoadState()
Clear/free saveload state.
bool _do_autosave
are we doing an autosave at the moment?
Definition saveload.cpp:86
static std::atomic< AsyncSaveFinishProc > _async_save_finish
Callback to call when the savegame loading is finished.
Definition saveload.cpp:378
static std::thread _save_thread
The thread we're using to compress and write a savegame.
Definition saveload.cpp:379
std::vector< SaveLoad > SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
Load a table header in a savegame compatible way.
static void ResetSettings()
Reset all settings to their default, so any settings missing in the savegame are their default,...
void SlWriteByte(uint8_t b)
Wrapper for writing a byte to the dumper.
Definition saveload.cpp:421
size_t SlGetStructListLength(size_t limit)
Get the length of this list; if it exceeds the limit, error out.
Label< struct SaveLoadFormatLabelTag > SaveLoadFormatTag
Unique 4-letter tag for the different saveload formats.
static SaveLoadResult DoLoad(std::shared_ptr< LoadFilter > reader, bool load_check)
Actually perform the loading of a "non-old" savegame.
SaveLoadResult SaveWithFilter(std::shared_ptr< SaveFilter > writer, bool threaded)
Save the game using a (writer) filter.
static size_t SlCalcArrayLen(size_t length, VarType conv)
Return the size in bytes of a certain type of atomic array.
void(* AsyncSaveFinishProc)()
Callback for when the savegame loading is finished.
Definition saveload.cpp:377
static const SaveLoadFormatTag SAVEGAME_TAG_LZMA
Tag for a game with lzma compression.
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition saveload.cpp:747
static const SaveLoadFormatTag SAVEGAME_TAG_LZO
Tag for a game compressed with LZO.
static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
Called by save thread to tell we finished saving.
Definition saveload.cpp:385
void SetSaveLoadError(StringID str)
Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friend...
void SlCopy(void *object, size_t length, VarType conv)
Copy a list of SaveLoadType::Variables to/from a savegame.
size_t SlGetFieldLength()
Get the length of the current object.
Definition saveload.cpp:873
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
static size_t SlCalcRefLen()
Return the size in bytes of a reference (pointer).
Definition saveload.cpp:730
NeedLength
Definition saveload.cpp:97
@ WantLength
writing length and data
Definition saveload.cpp:99
@ None
not working in NeedLength mode
Definition saveload.cpp:98
@ CalcLength
need to calculate the length
Definition saveload.cpp:100
static void SaveFileStart()
Update the gui accordingly when starting saving and set locks on saveload.
static void SlNullPointers()
Null all pointers (convert index -> nullptr).
Definition saveload.cpp:316
static void SlStdString(void *ptr, VarType conv)
Save/Load a std::string.
static size_t SlCalcRefListLen(const void *list, VarType conv)
Return the size in bytes of a list.
static bool SlIsObjectValidInSavegame(const SaveLoad &sld)
Are we going to save this object or not?
EncodedString GetSaveLoadErrorType()
Return the appropriate initial string for an error depending on whether we are saving or loading.
void SlSaveLoadRef(void *ptr, VarType conv)
Handle conversion for references.
static void SlFixPointers()
Fix all pointers (convert index -> pointer).
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition saveload.cpp:371
void SlSkipArray()
Skip an array or sparse array.
Definition saveload.cpp:789
static void SlLoadChunk(const ChunkHandler &ch)
Load a chunk of data (eg vehicles, stations, etc.).
static void SlLoadCheckChunks()
Load all chunks for savegame checking.
static size_t SlCalcStdStringLen(const void *ptr)
Calculate the gross length of the string that it will occupy in the savegame.
static uint SlReadSimpleGamma()
Read in the header descriptor of an object or an array.
Definition saveload.cpp:483
SaveLoadAction
What are we currently doing?
Definition saveload.cpp:89
@ Ptrs
fixing pointers
Definition saveload.cpp:92
@ Null
null all pointers (on loading error)
Definition saveload.cpp:93
@ LoadCheck
partial loading into _load_check_data
Definition saveload.cpp:94
@ Load
loading
Definition saveload.cpp:90
static void SlCopyBytes(void *ptr, size_t length)
Save/Load bytes.
Definition saveload.cpp:853
static ChunkId SlReadChunkId()
Read the ChunkId.
Definition saveload.cpp:467
static void SlCopyInternal(void *object, size_t length, VarType conv)
Internal function to save/Load a list of SaveLoadType::Variables.
static void SlArray(void *array, size_t length, VarType conv)
Save/Load the length of the array followed by the array of SaveLoadType::Variable elements.
static void SlSaveLoadConv(void *ptr, VarType conv)
Handle all conversion and typechecking of variables here.
Definition saveload.cpp:935
static const SaveLoadFormatTag SAVEGAME_TAG_NONE
Tag for a game without compression.
void WriteValue(void *ptr, VarMemType conv, int64_t val)
Write the value of a setting.
Definition saveload.cpp:909
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition saveload.cpp:80
static void SlLoadCheckChunk(const ChunkHandler &ch)
Load a chunk of data for checking savegames.
void SlSetLength(size_t length)
Sets the length of either a RIFF object or the number of items in an array.
Definition saveload.cpp:801
uint8_t SlReadByte()
Wrapper for reading a byte from the buffer.
Definition saveload.cpp:412
static SaveLoadParams _sl
Parameters used for/at saveload.
Definition saveload.cpp:220
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit).
static void SlLoadChunks()
Load all chunks.
static uint8_t SlCalcConvFileLen(VarType conv)
Return the size in bytes of a certain type of normal/atomic variable as it appears in a saved game.
Definition saveload.cpp:704
static void SlSaveChunk(const ChunkHandler &ch)
Save a chunk of data (eg.
size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt)
Calculate the size of an object.
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
EncodedString GetSaveLoadErrorMessage()
Return the description of the error.
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
bool AfterLoadGame()
Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill th...
SaveLoadResult LoadWithFilter(std::shared_ptr< LoadFilter > reader)
Load the game using a (reader) filter.
static void SlVector(void *vector, VarType conv)
Save/load a std::vector.
static void SaveFileError()
Show a gui message when saving has failed.
static SaveLoadResult SaveFileToDisk(bool threaded)
We have written the whole game into memory, _memory_savegame, now find and appropriate compressor and...
void SlGlobList(const SaveLoadTable &slt)
Save or Load (a list of) global variables.
static std::pair< const SaveLoadFormat &, uint8_t > GetSavegameFormat(std::string_view full_name)
Return the savegameformat of the game.
static uint SlCalcConvMemLen(VarMemType conv)
Return the size in bytes of a certain type of normal/atomic variable as it appears in memory.
Definition saveload.cpp:674
void FixSCCEncoded(std::string &str, bool fix_code)
Scan the string for old values of SCC_ENCODED and fix it to it's new, value.
static void SlSaveChunks()
Save all chunks.
std::string GenerateDefaultSaveName()
Get the default name for a savegame or screenshot.
static const size_t MEMORY_CHUNK_SIZE
Save in chunks of 128 KiB.
Definition saveload.cpp:104
int64_t ReadValue(const void *ptr, VarMemType conv)
Return a signed-long version of the value of a setting.
Definition saveload.cpp:885
void SlAutolength(AutolengthProc *proc, int arg)
Do something of which I have no idea what it is :P.
void SlReadString(std::string &str, size_t length)
Read the given amount of bytes from the buffer into the string.
static const SaveLoadFormatTag SAVEGAME_TAG_ZLIB
Tag for a game with zlib compression.
static const ChunkHandler * SlFindChunkHandler(ChunkId id)
Find the ChunkHandler that will be used for processing the found chunk in the savegame or in memory.
void SlSetStructListLength(size_t length)
Set the length of this list.
static uint SlGetGammaLength(size_t i)
Return how many bytes used to encode a gamma value.
Definition saveload.cpp:554
static const SaveLoadFormat * DetermineSaveLoadFormat(SaveLoadFormatTag tag, uint32_t raw_version)
Determines the SaveLoadFormat that is connected to the given tag.
static size_t SlCalcVectorLen(const void *vector, VarType conv)
Return the size in bytes of a std::vector.
static void SlRefList(void *list, VarType conv)
Save/Load a list.
VarMemType
The types/structures of data we have in memory.
Definition saveload.h:656
@ U64
A 64 bit unsigned int.
Definition saveload.h:665
@ Name
old custom name to be converted to a string pointer
Definition saveload.h:668
@ I8
A 8 bit signed int.
Definition saveload.h:658
@ U8
A 8 bit unsigned int.
Definition saveload.h:659
@ Label
A 4 character Label, stored as-is.
Definition saveload.h:669
@ Null
useful to write zeros in savegame.
Definition saveload.h:666
@ I16
A 16 bit signed int.
Definition saveload.h:660
@ Bool
A boolean value.
Definition saveload.h:657
@ U32
A 32 bit unsigned int.
Definition saveload.h:663
@ I32
A 32 bit signed int.
Definition saveload.h:662
@ I64
A 64 bit signed int.
Definition saveload.h:664
@ Str
string pointer
Definition saveload.h:667
@ U16
A 16 bit unsigned int.
Definition saveload.h:661
VarFileType
The types/structures of data that can be stored in the file.
Definition saveload.h:635
@ String
A string.
Definition saveload.h:650
@ U64
A 64 bit unsigned int.
Definition saveload.h:648
@ I8
A 8 bit signed int.
Definition saveload.h:639
@ U8
A 8 bit unsigned int.
Definition saveload.h:641
@ Struct
An arbitrary structure.
Definition saveload.h:651
@ I16
A 16 bit signed int.
Definition saveload.h:642
@ U32
A 32 bit unsigned int.
Definition saveload.h:645
@ StringID
StringID offset into strings-array.
Definition saveload.h:649
@ I32
A 32 bit signed int.
Definition saveload.h:644
@ I64
A 64 bit signed int.
Definition saveload.h:647
@ U16
A 16 bit unsigned int.
Definition saveload.h:643
SavegameType
Types of save games.
Definition saveload.h:432
@ OTTD
OTTD savegame.
Definition saveload.h:436
void SlSkipBytes(size_t length)
Read in bytes from the file/data structure but don't do anything with them, discarding them in effect...
Definition saveload.h:1321
SLRefType
Type of reference (SaveLoad::Reference, SaveLoad::ReferenceList, SaveLoad::ReferenceVector).
Definition saveload.h:621
@ LinkGraph
Load/save a reference to a link graph.
Definition saveload.h:630
@ CargoPacket
Load/save a reference to a cargo packet.
Definition saveload.h:627
@ OrderList
Load/save a reference to an orderlist.
Definition saveload.h:628
@ Station
Load/save a reference to a station.
Definition saveload.h:623
@ OldVehicle
Load/save an old-style reference to a vehicle (for pre-4.4 savegames).
Definition saveload.h:625
@ Storage
Load/save a reference to a persistent storage.
Definition saveload.h:629
@ Town
Load/save a reference to a town.
Definition saveload.h:624
@ LinkGraphJob
Load/save a reference to a link graph job.
Definition saveload.h:631
@ Vehicle
Load/save a reference to a vehicle.
Definition saveload.h:622
@ RoadStop
Load/save a reference to a bus/truck stop.
Definition saveload.h:626
void * GetVariableAddress(const void *object, const SaveLoad &sld)
Get the address of the variable.
Definition saveload.h:1264
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition saveload.h:515
SaveLoadType
Type of data saved.
Definition saveload.h:728
@ ReferenceList
Save/load a list of SaveLoadType::Reference elements.
Definition saveload.h:737
@ String
Save/load a std::string.
Definition saveload.h:733
@ Array
Save/load a fixed-size array of SaveLoadType::Variable elements.
Definition saveload.h:735
@ Variable
Save/load a variable.
Definition saveload.h:729
@ Vector
Save/load a vector of SaveLoadType::Variable elements.
Definition saveload.h:736
@ Reference
Save/load a reference.
Definition saveload.h:730
@ StructList
Save/load a list of structs.
Definition saveload.h:738
@ Struct
Save/load a struct.
Definition saveload.h:731
@ Null
Save null-bytes and load to nowhere.
Definition saveload.h:741
@ SaveByte
Save (but not load) a byte.
Definition saveload.h:740
@ ReferenceVector
Save/load a vector of SaveLoadType::Reference elements.
Definition saveload.h:743
std::span< const struct SaveLoadCompat > SaveLoadCompatTable
A table of SaveLoadCompat entries.
Definition saveload.h:518
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1223
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition saveload.h:34
@ EndPatchpacks
Saveload version: 286 Last known patchpack to use a version just above ours.
Definition saveload.h:326
@ MoveSccEncoded
Saveload version: 169, SVN revision: 23816 Move SCC_ENCODED to the first StringControlCode.
Definition saveload.h:250
@ TownTolerancePauseMode
Saveload version: 4.0, SVN revision: 1 Town council tolerance and pause mode.
Definition saveload.h:42
@ MoreCargoPackets
Saveload version: 69, SVN revision: 10319 Allow more than ~65k cargo packets.
Definition saveload.h:130
@ EncodedStringFormat
Saveload version: 350, GitHub pull request: 13499 Encoded String format changed.
Definition saveload.h:404
@ FixSccEncodedNegative
Saveload version: 353, GitHub pull request: 14049 Fix encoding of negative parameters.
Definition saveload.h:407
@ MinVersion
First savegame version.
Definition saveload.h:35
@ SaveloadListLength
Saveload version: 293, GitHub pull request: 9374 Consistency in list length with SaveLoadType::Struc...
Definition saveload.h:335
@ MaxVersion
Highest possible saveload version.
Definition saveload.h:428
@ StartPatchpacks
Saveload version: 220 First known patchpack to use a version just above ours.
Definition saveload.h:325
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
ChunkType
Type of a chunk.
Definition saveload.h:445
@ SparseTable
A SparseArray with a header describing the elements.
Definition saveload.h:450
@ ReadOnly
Chunk is never saved.
Definition saveload.h:453
@ Array
Contiguous array of elements starting at index 0.
Definition saveload.h:447
@ Table
An Array with a header describing the elements.
Definition saveload.h:449
@ FileTypeMask
All ChunkType values that are saved in the file have to be within this mask.
Definition saveload.h:452
@ Riff
4 bits store the chunk type, 28 bits the number of bytes.
Definition saveload.h:446
@ SparseArray
Array of elements with index for each element.
Definition saveload.h:448
Label< struct ChunkIdTag > ChunkId
Label/unique identifier for each of the chunks in the savegame.
Definition saveload.h:457
Functions/types related to errors from savegames.
void SlErrorCorruptFmt(const fmt::format_string< Args... > format, Args &&... fmt_args)
Issue an SlErrorCorrupt with a format string.
Declaration of filters used for saving and loading savegames.
std::shared_ptr< SaveFilter > CreateSaveFilter(std::shared_ptr< SaveFilter > chain, uint8_t compression_level)
Instantiator for a save filter.
std::shared_ptr< LoadFilter > CreateLoadFilter(std::shared_ptr< LoadFilter > chain)
Instantiator for a load filter.
Functions related to saving and loading games.
Declaration of functions used in more save/load files.
StringID RemapOldStringID(StringID s)
Remap a string ID from the old format to the new format.
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
SaveLoadResult
Save or load result codes.
@ Error
error that was caught before internal structures were modified
@ Ok
completed successfully
@ ReInit
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
std::span< const struct SaveLoad > SaveLoadTable
A table of SaveLoad entries.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
SettingTable GetSaveLoadSettingTable()
Create a single table with all settings that should be stored/loaded in the savegame.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Functions and types used internally for the settings configurations.
@ NotInSave
Do not save with savegame, basically client-based.
@ NoNetworkSync
Do not synchronize over network (but it is saved if SettingFlag::NotInSave is not set).
static constexpr const SettingDesc * GetSettingDesc(const SettingVariant &desc)
Helper to convert the type of the iterated settings description to a pointer to it.
Base classes/functions for stations.
Functions, definitions and such used only by the GUI.
@ SBI_SAVELOAD_FINISH
finished saving
@ SBI_SAVELOAD_START
started saving
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:261
void StrMakeValidInPlace(char *str, StringValidationSettings settings)
Scans the string for invalid characters and replaces them with a question mark '?
Definition string.cpp:156
Compose strings from textual and binary data.
Parse strings.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
Functions related to low-level strings.
@ ReplaceWithQuestionMark
Replace the unknown/bad bits with question marks.
Definition string_type.h:45
@ AllowControlCode
Allow the special control codes.
Definition string_type.h:47
EnumBitSet< StringValidationSetting, uint8_t > StringValidationSettings
Bitset of StringValidationSetting elements.
Definition string_type.h:57
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:335
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
Functions related to OTTD's strings.
Types related to strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Base for a four character label/tag/id.
constexpr bool Empty() const
Check whether the label is empty.
Container for cargo from the same location and time.
Definition cargopacket.h:40
Handlers and description of chunk.
Definition saveload.h:460
ChunkType type
Type of the chunk.
Definition saveload.h:462
virtual void LoadCheck(size_t len=0) const
Load the chunk for game preview.
ChunkId id
Unique ID (4 letters).
Definition saveload.h:461
std::string GetName() const
Get the name of this chunk.
Definition saveload.h:505
virtual void Load() const =0
Load the chunk.
virtual void Save() const
Save the chunk.
Definition saveload.h:478
size_t Read(uint8_t *buf, size_t size) override
Read a given number of bytes from the savegame.
void Reset() override
Reset this filter to read from the beginning of the file.
~FileReader() override
Make sure everything is cleaned up.
FileReader(FileHandle &&file)
Create the file reader, so it reads from a specific file.
long begin
The begin of the file.
std::optional< FileHandle > file
The file to read from.
Deals with the type of the savegame, independent of extension.
void SetMode(const FiosType &ft, SaveLoadOperation fop=SaveLoadOperation::Load)
Set the mode and file type of the file to save or load.
FiosType ftype
File type.
SaveLoadOperation file_op
File operation to perform.
std::string name
Name of the file.
EncodedString title
Internal name of the game.
void Set(const FiosItem &item)
Set the mode, title and name of the file.
std::optional< FileHandle > file
The file to write to.
void Write(const uint8_t *buf, size_t size) override
Write a given number of bytes into the savegame.
~FileWriter() override
Make sure everything is cleaned up.
FileWriter(FileHandle &&file)
Create the file writer, so it writes to a specific file.
void Finish() override
Prepare everything to finish writing the savegame.
Deals with finding savegames.
Definition fios.h:85
A savegame name automatically numbered.
Definition fios.h:127
std::string Filename()
Generate a savegame name and number according to _settings_client.gui.max_num_autosaves.
Definition fios.cpp:755
std::string Extension()
Generate an extension for a savegame name.
Definition fios.cpp:765
Elements of a file system that are recognized.
Definition fileio_type.h:62
AbstractFileType abstract
Abstract file type.
Definition fileio_type.h:63
lzma_stream lzma
Stream state that we are reading from.
size_t Read(uint8_t *buf, size_t size) override
Read a given number of bytes from the savegame.
~LZMALoadFilter() override
Clean everything up.
uint8_t fread_buf[MEMORY_CHUNK_SIZE]
Buffer for reading from the file.
LZMALoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
~LZMASaveFilter() override
Clean up what we allocated.
void WriteLoop(const uint8_t *p, size_t len, lzma_action action)
Helper loop for writing the data.
void Write(const uint8_t *buf, size_t size) override
Write a given number of bytes into the savegame.
void Finish() override
Prepare everything to finish writing the savegame.
LZMASaveFilter(std::shared_ptr< SaveFilter > chain, uint8_t compression_level)
Initialise this filter.
lzma_stream lzma
Stream state that we are writing to.
uint8_t fwrite_buf[MEMORY_CHUNK_SIZE]
Buffer for writing to the file.
LZOLoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
size_t Read(uint8_t *buf, size_t ssize) override
Read a given number of bytes from the savegame.
void Write(const uint8_t *buf, size_t size) override
Write a given number of bytes into the savegame.
LZOSaveFilter(std::shared_ptr< SaveFilter > chain, uint8_t)
Initialise this filter.
A four character label/tag/id.
std::shared_ptr< LoadFilter > chain
Chained to the (savegame) filters.
LoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
Container for dumping the savegame (quickly) to memory.
Definition saveload.cpp:148
uint8_t * buf
Buffer we're going to write to.
Definition saveload.cpp:150
void WriteByte(uint8_t b)
Write a single byte into the dumper.
Definition saveload.cpp:157
std::vector< std::unique_ptr< uint8_t[]> > blocks
Buffer with blocks of allocated memory.
Definition saveload.cpp:149
uint8_t * bufe
End of the buffer we write to.
Definition saveload.cpp:151
size_t GetSize() const
Get the size of the memory dump made so far.
Definition saveload.cpp:191
void Flush(std::shared_ptr< SaveFilter > writer)
Flush this dumper into a writer.
Definition saveload.cpp:172
NoCompLoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
size_t Read(uint8_t *buf, size_t size) override
Read a given number of bytes from the savegame.
void Write(const uint8_t *buf, size_t size) override
Write a given number of bytes into the savegame.
NoCompSaveFilter(std::shared_ptr< SaveFilter > chain, uint8_t)
Initialise this filter.
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:373
Class for pooled persistent storage of data.
static Pool::IterateWrapper< Company > Iterate(size_t from=0)
static OrderList * Get(auto index)
uint8_t * bufp
Location we're at reading the buffer.
Definition saveload.cpp:109
ReadBuffer(std::shared_ptr< LoadFilter > reader)
Initialise our variables.
Definition saveload.cpp:118
size_t read
The amount of read bytes so far from the filter.
Definition saveload.cpp:112
size_t GetSize() const
Get the size of the memory dump made so far.
Definition saveload.cpp:140
std::shared_ptr< LoadFilter > reader
The filter used to actually read.
Definition saveload.cpp:111
uint8_t buf[MEMORY_CHUNK_SIZE]
Buffer we're going to read from.
Definition saveload.cpp:108
uint8_t * bufe
End of the buffer we can read from.
Definition saveload.cpp:110
A Stop for a Road Vehicle.
SaveFilter(std::shared_ptr< SaveFilter > chain)
Initialise this filter.
std::shared_ptr< SaveFilter > chain
Chained to the (savegame) filters.
The format for a reader/writer type of a savegame.
uint8_t min_compression
the minimum compression level of this format
std::shared_ptr< SaveFilter >(* init_write)(std::shared_ptr< SaveFilter > chain, uint8_t compression)
Constructor for the save filter.
uint8_t default_compression
the default compression level of this format
std::shared_ptr< LoadFilter >(* init_load)(std::shared_ptr< LoadFilter > chain)
Constructor for the load filter.
SaveLoadFormatTag tag
the 4-letter tag by which it is identified in the savegame
std::string_view name
name of the compressor/decompressor (debug-only)
uint8_t max_compression
the maximum compression level of this format
The saveload struct, containing reader-writer functions, buffer, version, etc.
Definition saveload.cpp:198
std::unique_ptr< ReadBuffer > reader
Savegame reading buffer.
Definition saveload.cpp:211
std::shared_ptr< SaveFilter > sf
Filter to write the savegame to.
Definition saveload.cpp:209
ChunkType chunk_type
The type of chunk we are reading or writing.
Definition saveload.cpp:201
std::unique_ptr< MemoryDumper > dumper
Memory dumper to write the savegame to.
Definition saveload.cpp:208
StringID error_str
the translatable error message to show
Definition saveload.cpp:214
SaveLoadAction action
are we doing a save or a load atm.
Definition saveload.cpp:199
std::string extra_msg
the error message
Definition saveload.cpp:215
NeedLength need_length
working in NeedLength (Autolength) mode?
Definition saveload.cpp:200
bool saveinprogress
Whether there is currently a save in progress.
Definition saveload.cpp:217
std::shared_ptr< LoadFilter > lf
Filter to read the savegame from.
Definition saveload.cpp:212
bool expect_table_header
In the case of a table, if the header is saved/loaded.
Definition saveload.cpp:206
size_t obj_len
the length of the current object we are busy with
Definition saveload.cpp:204
bool error
did an error occur or not
Definition saveload.cpp:202
int last_array_index
in the case of an array, the current and last positions
Definition saveload.cpp:205
SaveLoad type struct.
Definition saveload.h:762
uint16_t length
(Conditional) length of the variable (eg. arrays) (max array size is 65536 elements).
Definition saveload.h:777
std::shared_ptr< SaveLoadHandler > handler
Custom handler for Save/Load procs.
Definition saveload.h:782
SaveLoadVersion version_to
Save/load the variable before this savegame version.
Definition saveload.h:779
SaveLoadType cmd
The action to take with the saved/loaded type, All types need different action.
Definition saveload.h:775
std::string name
Name of this field (optional, used for tables).
Definition saveload.h:774
VarType conv
Type of the variable to be saved; this field combines both FileVarType and MemVarType.
Definition saveload.h:776
SaveLoadVersion version_from
Save/load the variable starting from this savegame version.
Definition saveload.h:778
Container/wrapper for the file type that is used in tables in the save game.
Definition saveload.cpp:588
uint8_t storage
Actual storage of the file type.
Definition saveload.cpp:590
constexpr VarFileType Type() const
Get the VarType for this field.
Definition saveload.cpp:627
SavegameFileType(VarFileType file_type, bool has_field_length=false)
Create the type.
Definition saveload.cpp:600
constexpr bool HasFieldLength() const
Does this field have a length?
Definition saveload.cpp:617
constexpr bool IsEnd() const
Is this the end-of-table marker?
Definition saveload.cpp:611
static constexpr uint8_t HAS_FIELD_LENGTH_BIT
Set this bit to denote the type has a field length.
Definition saveload.cpp:589
SavegameFileType()
Create an end-of-table marker.
Definition saveload.cpp:593
Properties of config file settings.
SettingFlags flags
Handles how a setting would show up in the GUI (text/currency, etc.).
virtual void ResetToDefault(void *object) const =0
Reset the setting to its default value.
static Station * Get(auto index)
Station data structure.
Town data structure.
Definition town.h:64
Container of a variable's characteristics about a variable's storage.
Definition saveload.h:673
SLRefType ref
The reference type.
Definition saveload.h:677
VarMemType mem
The way of storing data in memory.
Definition saveload.h:675
StringValidationSettings string_validation_settings
Any settings related to validation of the strings.
Definition saveload.h:676
VarFileType file
The way of storing data in the file.
Definition saveload.h:674
static constexpr VarType U16
Store a 16 bits unsigned int.
Definition saveload.h:716
static constexpr VarType U8
Store a 8 bits unsigned int.
Definition saveload.h:714
static constexpr VarType STR
Store string.
Definition saveload.h:722
static constexpr VarType I16
Store a 16 bits signed int.
Definition saveload.h:715
static constexpr VarType I8
Store a 8 bits signed int.
Definition saveload.h:713
static constexpr VarType LABEL
Store a Label as-is.
Definition saveload.h:724
static constexpr VarType U32
Store a 32 bits unsigned int.
Definition saveload.h:718
static constexpr VarType STRINGID
Store a StringID.
Definition saveload.h:721
static constexpr VarType I32
Store a 32 bits signed int.
Definition saveload.h:717
Vehicle data structure.
size_t Read(uint8_t *buf, size_t size) override
Read a given number of bytes from the savegame.
ZlibLoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
uint8_t fread_buf[MEMORY_CHUNK_SIZE]
Buffer for reading from the file.
~ZlibLoadFilter() override
Clean everything up.
z_stream z
Stream state we are reading from.
z_stream z
Stream state we are writing to.
void Write(const uint8_t *buf, size_t size) override
Write a given number of bytes into the savegame.
uint8_t fwrite_buf[MEMORY_CHUNK_SIZE]
Buffer for writing to the file.
~ZlibSaveFilter() override
Clean up what we allocated.
void Finish() override
Prepare everything to finish writing the savegame.
ZlibSaveFilter(std::shared_ptr< SaveFilter > chain, uint8_t compression_level)
Initialise this filter.
void WriteLoop(const uint8_t *p, size_t len, int mode)
Helper loop for writing the data.
Base of all threads.
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition thread.h:24
bool StartNewThread(std::thread *thr, std::string_view name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition thread.h:47
Definition of the game-economy-timer.
Base of the town class.
Base class for all vehicles.
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
Window functions not directly related to making/drawing windows.