OpenTTD Source  13.0-beta2
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 <http://www.gnu.org/licenses/>.
6  */
7 
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"
31 #include "../core/endian_func.hpp"
32 #include "../vehicle_base.h"
33 #include "../company_func.h"
34 #include "../date_func.h"
35 #include "../autoreplace_base.h"
36 #include "../roadstop_base.h"
37 #include "../linkgraph/linkgraph.h"
38 #include "../linkgraph/linkgraphjob.h"
39 #include "../statusbar_gui.h"
40 #include "../fileio_func.h"
41 #include "../gamelog.h"
42 #include "../string_func.h"
43 #include "../fios.h"
44 #include "../error.h"
45 #include <atomic>
46 #include <deque>
47 #include <vector>
48 #include <string>
49 #ifdef __EMSCRIPTEN__
50 # include <emscripten.h>
51 #endif
52 
53 #include "table/strings.h"
54 
55 #include "saveload_internal.h"
56 #include "saveload_filter.h"
57 
58 #include "../safeguards.h"
59 
61 
64 
65 uint32 _ttdp_version;
68 std::string _savegame_format;
70 
78 };
79 
80 enum NeedLength {
81  NL_NONE = 0,
84 };
85 
87 static const size_t MEMORY_CHUNK_SIZE = 128 * 1024;
88 
90 struct ReadBuffer {
92  byte *bufp;
93  byte *bufe;
95  size_t read;
96 
101  ReadBuffer(LoadFilter *reader) : bufp(nullptr), bufe(nullptr), reader(reader), read(0)
102  {
103  }
104 
105  inline byte ReadByte()
106  {
107  if (this->bufp == this->bufe) {
108  size_t len = this->reader->Read(this->buf, lengthof(this->buf));
109  if (len == 0) SlErrorCorrupt("Unexpected end of chunk");
110 
111  this->read += len;
112  this->bufp = this->buf;
113  this->bufe = this->buf + len;
114  }
115 
116  return *this->bufp++;
117  }
118 
123  size_t GetSize() const
124  {
125  return this->read - (this->bufe - this->bufp);
126  }
127 };
128 
129 
131 struct MemoryDumper {
132  std::vector<byte *> blocks;
133  byte *buf;
134  byte *bufe;
135 
137  MemoryDumper() : buf(nullptr), bufe(nullptr)
138  {
139  }
140 
141  ~MemoryDumper()
142  {
143  for (auto p : this->blocks) {
144  free(p);
145  }
146  }
147 
152  inline void WriteByte(byte b)
153  {
154  /* Are we at the end of this chunk? */
155  if (this->buf == this->bufe) {
156  this->buf = CallocT<byte>(MEMORY_CHUNK_SIZE);
157  this->blocks.push_back(this->buf);
158  this->bufe = this->buf + MEMORY_CHUNK_SIZE;
159  }
160 
161  *this->buf++ = b;
162  }
163 
168  void Flush(SaveFilter *writer)
169  {
170  uint i = 0;
171  size_t t = this->GetSize();
172 
173  while (t > 0) {
174  size_t to_write = std::min(MEMORY_CHUNK_SIZE, t);
175 
176  writer->Write(this->blocks[i++], to_write);
177  t -= to_write;
178  }
179 
180  writer->Finish();
181  }
182 
187  size_t GetSize() const
188  {
189  return this->blocks.size() * MEMORY_CHUNK_SIZE - (this->bufe - this->buf);
190  }
191 };
192 
197  byte block_mode;
198  bool error;
199 
200  size_t obj_len;
201  int array_index, last_array_index;
203 
206 
209 
211  char *extra_msg;
212 
213  uint16 game_speed;
215 };
216 
218 
219 static const std::vector<ChunkHandlerRef> &ChunkHandlers()
220 {
221  /* These define the chunks */
222  extern const ChunkHandlerTable _gamelog_chunk_handlers;
223  extern const ChunkHandlerTable _map_chunk_handlers;
224  extern const ChunkHandlerTable _misc_chunk_handlers;
225  extern const ChunkHandlerTable _name_chunk_handlers;
226  extern const ChunkHandlerTable _cheat_chunk_handlers;
227  extern const ChunkHandlerTable _setting_chunk_handlers;
228  extern const ChunkHandlerTable _company_chunk_handlers;
229  extern const ChunkHandlerTable _engine_chunk_handlers;
230  extern const ChunkHandlerTable _veh_chunk_handlers;
231  extern const ChunkHandlerTable _waypoint_chunk_handlers;
232  extern const ChunkHandlerTable _depot_chunk_handlers;
233  extern const ChunkHandlerTable _order_chunk_handlers;
234  extern const ChunkHandlerTable _town_chunk_handlers;
235  extern const ChunkHandlerTable _sign_chunk_handlers;
236  extern const ChunkHandlerTable _station_chunk_handlers;
237  extern const ChunkHandlerTable _industry_chunk_handlers;
238  extern const ChunkHandlerTable _economy_chunk_handlers;
239  extern const ChunkHandlerTable _subsidy_chunk_handlers;
240  extern const ChunkHandlerTable _cargomonitor_chunk_handlers;
241  extern const ChunkHandlerTable _goal_chunk_handlers;
242  extern const ChunkHandlerTable _story_page_chunk_handlers;
243  extern const ChunkHandlerTable _league_chunk_handlers;
244  extern const ChunkHandlerTable _ai_chunk_handlers;
245  extern const ChunkHandlerTable _game_chunk_handlers;
246  extern const ChunkHandlerTable _animated_tile_chunk_handlers;
247  extern const ChunkHandlerTable _newgrf_chunk_handlers;
248  extern const ChunkHandlerTable _group_chunk_handlers;
249  extern const ChunkHandlerTable _cargopacket_chunk_handlers;
250  extern const ChunkHandlerTable _autoreplace_chunk_handlers;
251  extern const ChunkHandlerTable _labelmaps_chunk_handlers;
252  extern const ChunkHandlerTable _linkgraph_chunk_handlers;
253  extern const ChunkHandlerTable _airport_chunk_handlers;
254  extern const ChunkHandlerTable _object_chunk_handlers;
255  extern const ChunkHandlerTable _persistent_storage_chunk_handlers;
256 
258  static const ChunkHandlerTable _chunk_handler_tables[] = {
259  _gamelog_chunk_handlers,
260  _map_chunk_handlers,
261  _misc_chunk_handlers,
262  _name_chunk_handlers,
263  _cheat_chunk_handlers,
264  _setting_chunk_handlers,
265  _veh_chunk_handlers,
266  _waypoint_chunk_handlers,
267  _depot_chunk_handlers,
268  _order_chunk_handlers,
269  _industry_chunk_handlers,
270  _economy_chunk_handlers,
271  _subsidy_chunk_handlers,
272  _cargomonitor_chunk_handlers,
273  _goal_chunk_handlers,
274  _story_page_chunk_handlers,
275  _league_chunk_handlers,
276  _engine_chunk_handlers,
277  _town_chunk_handlers,
278  _sign_chunk_handlers,
279  _station_chunk_handlers,
280  _company_chunk_handlers,
281  _ai_chunk_handlers,
282  _game_chunk_handlers,
283  _animated_tile_chunk_handlers,
284  _newgrf_chunk_handlers,
285  _group_chunk_handlers,
286  _cargopacket_chunk_handlers,
287  _autoreplace_chunk_handlers,
288  _labelmaps_chunk_handlers,
289  _linkgraph_chunk_handlers,
290  _airport_chunk_handlers,
291  _object_chunk_handlers,
292  _persistent_storage_chunk_handlers,
293  };
294 
295  static std::vector<ChunkHandlerRef> _chunk_handlers;
296 
297  if (_chunk_handlers.empty()) {
298  for (auto &chunk_handler_table : _chunk_handler_tables) {
299  for (auto &chunk_handler : chunk_handler_table) {
300  _chunk_handlers.push_back(chunk_handler);
301  }
302  }
303  }
304 
305  return _chunk_handlers;
306 }
307 
309 static void SlNullPointers()
310 {
311  _sl.action = SLA_NULL;
312 
313  /* We don't want any savegame conversion code to run
314  * during NULLing; especially those that try to get
315  * pointers from other pools. */
317 
318  for (const ChunkHandler &ch : ChunkHandlers()) {
319  Debug(sl, 3, "Nulling pointers for {:c}{:c}{:c}{:c}", ch.id >> 24, ch.id >> 16, ch.id >> 8, ch.id);
320  ch.FixPointers();
321  }
322 
323  assert(_sl.action == SLA_NULL);
324 }
325 
334 void NORETURN SlError(StringID string, const char *extra_msg)
335 {
336  /* Distinguish between loading into _load_check_data vs. normal save/load. */
337  if (_sl.action == SLA_LOAD_CHECK) {
338  _load_check_data.error = string;
340  _load_check_data.error_data = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
341  } else {
342  _sl.error_str = string;
343  free(_sl.extra_msg);
344  _sl.extra_msg = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
345  }
346 
347  /* We have to nullptr all pointers here; we might be in a state where
348  * the pointers are actually filled with indices, which means that
349  * when we access them during cleaning the pool dereferences of
350  * those indices will be made with segmentation faults as result. */
352 
353  /* Logging could be active. */
354  GamelogStopAnyAction();
355 
356  throw std::exception();
357 }
358 
366 void NORETURN SlErrorCorrupt(const char *msg)
367 {
368  SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, msg);
369 }
370 
378 void NORETURN SlErrorCorruptFmt(const char *format, ...)
379 {
380  va_list ap;
381  char msg[256];
382 
383  va_start(ap, format);
384  vseprintf(msg, lastof(msg), format, ap);
385  va_end(ap);
386 
387  SlErrorCorrupt(msg);
388 }
389 
390 
391 typedef void (*AsyncSaveFinishProc)();
392 static std::atomic<AsyncSaveFinishProc> _async_save_finish;
393 static std::thread _save_thread;
394 
400 {
401  if (_exit_game) return;
402  while (_async_save_finish.load(std::memory_order_acquire) != nullptr) CSleep(10);
403 
404  _async_save_finish.store(proc, std::memory_order_release);
405 }
406 
411 {
412  AsyncSaveFinishProc proc = _async_save_finish.exchange(nullptr, std::memory_order_acq_rel);
413  if (proc == nullptr) return;
414 
415  proc();
416 
417  if (_save_thread.joinable()) {
418  _save_thread.join();
419  }
420 }
421 
427 {
428  return _sl.reader->ReadByte();
429 }
430 
435 void SlWriteByte(byte b)
436 {
437  _sl.dumper->WriteByte(b);
438 }
439 
440 static inline int SlReadUint16()
441 {
442  int x = SlReadByte() << 8;
443  return x | SlReadByte();
444 }
445 
446 static inline uint32 SlReadUint32()
447 {
448  uint32 x = SlReadUint16() << 16;
449  return x | SlReadUint16();
450 }
451 
452 static inline uint64 SlReadUint64()
453 {
454  uint32 x = SlReadUint32();
455  uint32 y = SlReadUint32();
456  return (uint64)x << 32 | y;
457 }
458 
459 static inline void SlWriteUint16(uint16 v)
460 {
461  SlWriteByte(GB(v, 8, 8));
462  SlWriteByte(GB(v, 0, 8));
463 }
464 
465 static inline void SlWriteUint32(uint32 v)
466 {
467  SlWriteUint16(GB(v, 16, 16));
468  SlWriteUint16(GB(v, 0, 16));
469 }
470 
471 static inline void SlWriteUint64(uint64 x)
472 {
473  SlWriteUint32((uint32)(x >> 32));
474  SlWriteUint32((uint32)x);
475 }
476 
486 static uint SlReadSimpleGamma()
487 {
488  uint i = SlReadByte();
489  if (HasBit(i, 7)) {
490  i &= ~0x80;
491  if (HasBit(i, 6)) {
492  i &= ~0x40;
493  if (HasBit(i, 5)) {
494  i &= ~0x20;
495  if (HasBit(i, 4)) {
496  i &= ~0x10;
497  if (HasBit(i, 3)) {
498  SlErrorCorrupt("Unsupported gamma");
499  }
500  i = SlReadByte(); // 32 bits only.
501  }
502  i = (i << 8) | SlReadByte();
503  }
504  i = (i << 8) | SlReadByte();
505  }
506  i = (i << 8) | SlReadByte();
507  }
508  return i;
509 }
510 
528 static void SlWriteSimpleGamma(size_t i)
529 {
530  if (i >= (1 << 7)) {
531  if (i >= (1 << 14)) {
532  if (i >= (1 << 21)) {
533  if (i >= (1 << 28)) {
534  assert(i <= UINT32_MAX); // We can only support 32 bits for now.
535  SlWriteByte((byte)(0xF0));
536  SlWriteByte((byte)(i >> 24));
537  } else {
538  SlWriteByte((byte)(0xE0 | (i >> 24)));
539  }
540  SlWriteByte((byte)(i >> 16));
541  } else {
542  SlWriteByte((byte)(0xC0 | (i >> 16)));
543  }
544  SlWriteByte((byte)(i >> 8));
545  } else {
546  SlWriteByte((byte)(0x80 | (i >> 8)));
547  }
548  }
549  SlWriteByte((byte)i);
550 }
551 
553 static inline uint SlGetGammaLength(size_t i)
554 {
555  return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21)) + (i >= (1 << 28));
556 }
557 
558 static inline uint SlReadSparseIndex()
559 {
560  return SlReadSimpleGamma();
561 }
562 
563 static inline void SlWriteSparseIndex(uint index)
564 {
565  SlWriteSimpleGamma(index);
566 }
567 
568 static inline uint SlReadArrayLength()
569 {
570  return SlReadSimpleGamma();
571 }
572 
573 static inline void SlWriteArrayLength(size_t length)
574 {
575  SlWriteSimpleGamma(length);
576 }
577 
578 static inline uint SlGetArrayLength(size_t length)
579 {
580  return SlGetGammaLength(length);
581 }
582 
586 static uint8 GetSavegameFileType(const SaveLoad &sld)
587 {
588  switch (sld.cmd) {
589  case SL_VAR:
590  return GetVarFileType(sld.conv); break;
591 
592  case SL_STR:
593  case SL_STDSTR:
594  case SL_ARR:
595  case SL_VECTOR:
596  case SL_DEQUE:
597  return GetVarFileType(sld.conv) | SLE_FILE_HAS_LENGTH_FIELD; break;
598 
599  case SL_REF:
600  return IsSavegameVersionBefore(SLV_69) ? SLE_FILE_U16 : SLE_FILE_U32;
601 
602  case SL_REFLIST:
603  return (IsSavegameVersionBefore(SLV_69) ? SLE_FILE_U16 : SLE_FILE_U32) | SLE_FILE_HAS_LENGTH_FIELD;
604 
605  case SL_SAVEBYTE:
606  return SLE_FILE_U8;
607 
608  case SL_STRUCT:
609  case SL_STRUCTLIST:
610  return SLE_FILE_STRUCT | SLE_FILE_HAS_LENGTH_FIELD;
611 
612  default: NOT_REACHED();
613  }
614 }
615 
622 static inline uint SlCalcConvMemLen(VarType conv)
623 {
624  static const byte conv_mem_size[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
625 
626  switch (GetVarMemType(conv)) {
627  case SLE_VAR_STRB:
628  case SLE_VAR_STR:
629  case SLE_VAR_STRQ:
630  return SlReadArrayLength();
631 
632  default:
633  uint8 type = GetVarMemType(conv) >> 4;
634  assert(type < lengthof(conv_mem_size));
635  return conv_mem_size[type];
636  }
637 }
638 
645 static inline byte SlCalcConvFileLen(VarType conv)
646 {
647  static const byte conv_file_size[] = {0, 1, 1, 2, 2, 4, 4, 8, 8, 2};
648 
649  uint8 type = GetVarFileType(conv);
650  assert(type < lengthof(conv_file_size));
651  return conv_file_size[type];
652 }
653 
655 static inline size_t SlCalcRefLen()
656 {
657  return IsSavegameVersionBefore(SLV_69) ? 2 : 4;
658 }
659 
660 void SlSetArrayIndex(uint index)
661 {
663  _sl.array_index = index;
664 }
665 
666 static size_t _next_offs;
667 
673 {
674  int index;
675 
676  /* After reading in the whole array inside the loop
677  * we must have read in all the data, so we must be at end of current block. */
678  if (_next_offs != 0 && _sl.reader->GetSize() != _next_offs) SlErrorCorrupt("Invalid chunk size");
679 
680  for (;;) {
681  uint length = SlReadArrayLength();
682  if (length == 0) {
683  assert(!_sl.expect_table_header);
684  _next_offs = 0;
685  return -1;
686  }
687 
688  _sl.obj_len = --length;
689  _next_offs = _sl.reader->GetSize() + length;
690 
691  if (_sl.expect_table_header) {
692  _sl.expect_table_header = false;
693  return INT32_MAX;
694  }
695 
696  switch (_sl.block_mode) {
697  case CH_SPARSE_TABLE:
698  case CH_SPARSE_ARRAY: index = (int)SlReadSparseIndex(); break;
699  case CH_TABLE:
700  case CH_ARRAY: index = _sl.array_index++; break;
701  default:
702  Debug(sl, 0, "SlIterateArray error");
703  return -1; // error
704  }
705 
706  if (length != 0) return index;
707  }
708 }
709 
714 {
715  while (SlIterateArray() != -1) {
716  SlSkipBytes(_next_offs - _sl.reader->GetSize());
717  }
718 }
719 
725 void SlSetLength(size_t length)
726 {
727  assert(_sl.action == SLA_SAVE);
728 
729  switch (_sl.need_length) {
730  case NL_WANTLENGTH:
732  if ((_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE) && _sl.expect_table_header) {
733  _sl.expect_table_header = false;
734  SlWriteArrayLength(length + 1);
735  break;
736  }
737 
738  switch (_sl.block_mode) {
739  case CH_RIFF:
740  /* Ugly encoding of >16M RIFF chunks
741  * The lower 24 bits are normal
742  * The uppermost 4 bits are bits 24:27 */
743  assert(length < (1 << 28));
744  SlWriteUint32((uint32)((length & 0xFFFFFF) | ((length >> 24) << 28)));
745  break;
746  case CH_TABLE:
747  case CH_ARRAY:
748  assert(_sl.last_array_index <= _sl.array_index);
749  while (++_sl.last_array_index <= _sl.array_index) {
750  SlWriteArrayLength(1);
751  }
752  SlWriteArrayLength(length + 1);
753  break;
754  case CH_SPARSE_TABLE:
755  case CH_SPARSE_ARRAY:
756  SlWriteArrayLength(length + 1 + SlGetArrayLength(_sl.array_index)); // Also include length of sparse index.
757  SlWriteSparseIndex(_sl.array_index);
758  break;
759  default: NOT_REACHED();
760  }
761  break;
762 
763  case NL_CALCLENGTH:
764  _sl.obj_len += (int)length;
765  break;
766 
767  default: NOT_REACHED();
768  }
769 }
770 
777 static void SlCopyBytes(void *ptr, size_t length)
778 {
779  byte *p = (byte *)ptr;
780 
781  switch (_sl.action) {
782  case SLA_LOAD_CHECK:
783  case SLA_LOAD:
784  for (; length != 0; length--) *p++ = SlReadByte();
785  break;
786  case SLA_SAVE:
787  for (; length != 0; length--) SlWriteByte(*p++);
788  break;
789  default: NOT_REACHED();
790  }
791 }
792 
795 {
796  return _sl.obj_len;
797 }
798 
806 int64 ReadValue(const void *ptr, VarType conv)
807 {
808  switch (GetVarMemType(conv)) {
809  case SLE_VAR_BL: return (*(const bool *)ptr != 0);
810  case SLE_VAR_I8: return *(const int8 *)ptr;
811  case SLE_VAR_U8: return *(const byte *)ptr;
812  case SLE_VAR_I16: return *(const int16 *)ptr;
813  case SLE_VAR_U16: return *(const uint16*)ptr;
814  case SLE_VAR_I32: return *(const int32 *)ptr;
815  case SLE_VAR_U32: return *(const uint32*)ptr;
816  case SLE_VAR_I64: return *(const int64 *)ptr;
817  case SLE_VAR_U64: return *(const uint64*)ptr;
818  case SLE_VAR_NULL:return 0;
819  default: NOT_REACHED();
820  }
821 }
822 
830 void WriteValue(void *ptr, VarType conv, int64 val)
831 {
832  switch (GetVarMemType(conv)) {
833  case SLE_VAR_BL: *(bool *)ptr = (val != 0); break;
834  case SLE_VAR_I8: *(int8 *)ptr = val; break;
835  case SLE_VAR_U8: *(byte *)ptr = val; break;
836  case SLE_VAR_I16: *(int16 *)ptr = val; break;
837  case SLE_VAR_U16: *(uint16*)ptr = val; break;
838  case SLE_VAR_I32: *(int32 *)ptr = val; break;
839  case SLE_VAR_U32: *(uint32*)ptr = val; break;
840  case SLE_VAR_I64: *(int64 *)ptr = val; break;
841  case SLE_VAR_U64: *(uint64*)ptr = val; break;
842  case SLE_VAR_NAME: *reinterpret_cast<std::string *>(ptr) = CopyFromOldName(val); break;
843  case SLE_VAR_NULL: break;
844  default: NOT_REACHED();
845  }
846 }
847 
856 static void SlSaveLoadConv(void *ptr, VarType conv)
857 {
858  switch (_sl.action) {
859  case SLA_SAVE: {
860  int64 x = ReadValue(ptr, conv);
861 
862  /* Write the value to the file and check if its value is in the desired range */
863  switch (GetVarFileType(conv)) {
864  case SLE_FILE_I8: assert(x >= -128 && x <= 127); SlWriteByte(x);break;
865  case SLE_FILE_U8: assert(x >= 0 && x <= 255); SlWriteByte(x);break;
866  case SLE_FILE_I16:assert(x >= -32768 && x <= 32767); SlWriteUint16(x);break;
867  case SLE_FILE_STRINGID:
868  case SLE_FILE_U16:assert(x >= 0 && x <= 65535); SlWriteUint16(x);break;
869  case SLE_FILE_I32:
870  case SLE_FILE_U32: SlWriteUint32((uint32)x);break;
871  case SLE_FILE_I64:
872  case SLE_FILE_U64: SlWriteUint64(x);break;
873  default: NOT_REACHED();
874  }
875  break;
876  }
877  case SLA_LOAD_CHECK:
878  case SLA_LOAD: {
879  int64 x;
880  /* Read a value from the file */
881  switch (GetVarFileType(conv)) {
882  case SLE_FILE_I8: x = (int8 )SlReadByte(); break;
883  case SLE_FILE_U8: x = (byte )SlReadByte(); break;
884  case SLE_FILE_I16: x = (int16 )SlReadUint16(); break;
885  case SLE_FILE_U16: x = (uint16)SlReadUint16(); break;
886  case SLE_FILE_I32: x = (int32 )SlReadUint32(); break;
887  case SLE_FILE_U32: x = (uint32)SlReadUint32(); break;
888  case SLE_FILE_I64: x = (int64 )SlReadUint64(); break;
889  case SLE_FILE_U64: x = (uint64)SlReadUint64(); break;
890  case SLE_FILE_STRINGID: x = RemapOldStringID((uint16)SlReadUint16()); break;
891  default: NOT_REACHED();
892  }
893 
894  /* Write The value to the struct. These ARE endian safe. */
895  WriteValue(ptr, conv, x);
896  break;
897  }
898  case SLA_PTRS: break;
899  case SLA_NULL: break;
900  default: NOT_REACHED();
901  }
902 }
903 
913 static inline size_t SlCalcNetStringLen(const char *ptr, size_t length)
914 {
915  if (ptr == nullptr) return 0;
916  return std::min(strlen(ptr), length - 1);
917 }
918 
928 static inline size_t SlCalcStringLen(const void *ptr, size_t length, VarType conv)
929 {
930  size_t len;
931  const char *str;
932 
933  switch (GetVarMemType(conv)) {
934  default: NOT_REACHED();
935  case SLE_VAR_STR:
936  case SLE_VAR_STRQ:
937  str = *(const char * const *)ptr;
938  len = SIZE_MAX;
939  break;
940  case SLE_VAR_STRB:
941  str = (const char *)ptr;
942  len = length;
943  break;
944  }
945 
946  len = SlCalcNetStringLen(str, len);
947  return len + SlGetArrayLength(len); // also include the length of the index
948 }
949 
957 static inline size_t SlCalcStdStringLen(const void *ptr)
958 {
959  const std::string *str = reinterpret_cast<const std::string *>(ptr);
960 
961  size_t len = str->length();
962  return len + SlGetArrayLength(len); // also include the length of the index
963 }
964 
971 static void SlString(void *ptr, size_t length, VarType conv)
972 {
973  switch (_sl.action) {
974  case SLA_SAVE: {
975  size_t len;
976  switch (GetVarMemType(conv)) {
977  default: NOT_REACHED();
978  case SLE_VAR_STRB:
979  len = SlCalcNetStringLen((char *)ptr, length);
980  break;
981  case SLE_VAR_STR:
982  case SLE_VAR_STRQ:
983  ptr = *(char **)ptr;
984  len = SlCalcNetStringLen((char *)ptr, SIZE_MAX);
985  break;
986  }
987 
988  SlWriteArrayLength(len);
989  SlCopyBytes(ptr, len);
990  break;
991  }
992  case SLA_LOAD_CHECK:
993  case SLA_LOAD: {
994  size_t len = SlReadArrayLength();
995 
996  switch (GetVarMemType(conv)) {
997  default: NOT_REACHED();
998  case SLE_VAR_NULL:
999  SlSkipBytes(len);
1000  return;
1001  case SLE_VAR_STRB:
1002  if (len >= length) {
1003  Debug(sl, 1, "String length in savegame is bigger than buffer, truncating");
1004  SlCopyBytes(ptr, length);
1005  SlSkipBytes(len - length);
1006  len = length - 1;
1007  } else {
1008  SlCopyBytes(ptr, len);
1009  }
1010  break;
1011  case SLE_VAR_STR:
1012  case SLE_VAR_STRQ: // Malloc'd string, free previous incarnation, and allocate
1013  free(*(char **)ptr);
1014  if (len == 0) {
1015  *(char **)ptr = nullptr;
1016  return;
1017  } else {
1018  *(char **)ptr = MallocT<char>(len + 1); // terminating '\0'
1019  ptr = *(char **)ptr;
1020  SlCopyBytes(ptr, len);
1021  }
1022  break;
1023  }
1024 
1025  ((char *)ptr)[len] = '\0'; // properly terminate the string
1027  if ((conv & SLF_ALLOW_CONTROL) != 0) {
1030  str_fix_scc_encoded((char *)ptr, (char *)ptr + len);
1031  }
1032  }
1033  if ((conv & SLF_ALLOW_NEWLINE) != 0) {
1035  }
1036  StrMakeValidInPlace((char *)ptr, (char *)ptr + len, settings);
1037  break;
1038  }
1039  case SLA_PTRS: break;
1040  case SLA_NULL: break;
1041  default: NOT_REACHED();
1042  }
1043 }
1044 
1050 static void SlStdString(void *ptr, VarType conv)
1051 {
1052  std::string *str = reinterpret_cast<std::string *>(ptr);
1053 
1054  switch (_sl.action) {
1055  case SLA_SAVE: {
1056  size_t len = str->length();
1057  SlWriteArrayLength(len);
1058  SlCopyBytes(const_cast<void *>(static_cast<const void *>(str->c_str())), len);
1059  break;
1060  }
1061 
1062  case SLA_LOAD_CHECK:
1063  case SLA_LOAD: {
1064  size_t len = SlReadArrayLength();
1065  if (GetVarMemType(conv) == SLE_VAR_NULL) {
1066  SlSkipBytes(len);
1067  return;
1068  }
1069 
1070  char *buf = AllocaM(char, len + 1);
1071  SlCopyBytes(buf, len);
1072  buf[len] = '\0'; // properly terminate the string
1073 
1075  if ((conv & SLF_ALLOW_CONTROL) != 0) {
1078  str_fix_scc_encoded(buf, buf + len);
1079  }
1080  }
1081  if ((conv & SLF_ALLOW_NEWLINE) != 0) {
1083  }
1084  StrMakeValidInPlace(buf, buf + len, settings);
1085 
1086  // Store sanitized string.
1087  str->assign(buf);
1088  }
1089 
1090  case SLA_PTRS: break;
1091  case SLA_NULL: break;
1092  default: NOT_REACHED();
1093  }
1094 }
1095 
1104 static void SlCopyInternal(void *object, size_t length, VarType conv)
1105 {
1106  if (GetVarMemType(conv) == SLE_VAR_NULL) {
1107  assert(_sl.action != SLA_SAVE); // Use SL_NULL if you want to write null-bytes
1108  SlSkipBytes(length * SlCalcConvFileLen(conv));
1109  return;
1110  }
1111 
1112  /* NOTICE - handle some buggy stuff, in really old versions everything was saved
1113  * as a byte-type. So detect this, and adjust object size accordingly */
1114  if (_sl.action != SLA_SAVE && _sl_version == 0) {
1115  /* all objects except difficulty settings */
1116  if (conv == SLE_INT16 || conv == SLE_UINT16 || conv == SLE_STRINGID ||
1117  conv == SLE_INT32 || conv == SLE_UINT32) {
1118  SlCopyBytes(object, length * SlCalcConvFileLen(conv));
1119  return;
1120  }
1121  /* used for conversion of Money 32bit->64bit */
1122  if (conv == (SLE_FILE_I32 | SLE_VAR_I64)) {
1123  for (uint i = 0; i < length; i++) {
1124  ((int64*)object)[i] = (int32)BSWAP32(SlReadUint32());
1125  }
1126  return;
1127  }
1128  }
1129 
1130  /* If the size of elements is 1 byte both in file and memory, no special
1131  * conversion is needed, use specialized copy-copy function to speed up things */
1132  if (conv == SLE_INT8 || conv == SLE_UINT8) {
1133  SlCopyBytes(object, length);
1134  } else {
1135  byte *a = (byte*)object;
1136  byte mem_size = SlCalcConvMemLen(conv);
1137 
1138  for (; length != 0; length --) {
1139  SlSaveLoadConv(a, conv);
1140  a += mem_size; // get size
1141  }
1142  }
1143 }
1144 
1153 void SlCopy(void *object, size_t length, VarType conv)
1154 {
1155  if (_sl.action == SLA_PTRS || _sl.action == SLA_NULL) return;
1156 
1157  /* Automatically calculate the length? */
1158  if (_sl.need_length != NL_NONE) {
1159  SlSetLength(length * SlCalcConvFileLen(conv));
1160  /* Determine length only? */
1161  if (_sl.need_length == NL_CALCLENGTH) return;
1162  }
1163 
1164  SlCopyInternal(object, length, conv);
1165 }
1166 
1172 static inline size_t SlCalcArrayLen(size_t length, VarType conv)
1173 {
1174  return SlCalcConvFileLen(conv) * length + SlGetArrayLength(length);
1175 }
1176 
1183 static void SlArray(void *array, size_t length, VarType conv)
1184 {
1185  switch (_sl.action) {
1186  case SLA_SAVE:
1187  SlWriteArrayLength(length);
1188  SlCopyInternal(array, length, conv);
1189  return;
1190 
1191  case SLA_LOAD_CHECK:
1192  case SLA_LOAD: {
1194  size_t sv_length = SlReadArrayLength();
1195  if (GetVarMemType(conv) == SLE_VAR_NULL) {
1196  /* We don't know this field, so we assume the length in the savegame is correct. */
1197  length = sv_length;
1198  } else if (sv_length != length) {
1199  /* If the SLE_ARR changes size, a savegame bump is required
1200  * and the developer should have written conversion lines.
1201  * Error out to make this more visible. */
1202  SlErrorCorrupt("Fixed-length array is of wrong length");
1203  }
1204  }
1205 
1206  SlCopyInternal(array, length, conv);
1207  return;
1208  }
1209 
1210  case SLA_PTRS:
1211  case SLA_NULL:
1212  return;
1213 
1214  default:
1215  NOT_REACHED();
1216  }
1217 }
1218 
1229 static size_t ReferenceToInt(const void *obj, SLRefType rt)
1230 {
1231  assert(_sl.action == SLA_SAVE);
1232 
1233  if (obj == nullptr) return 0;
1234 
1235  switch (rt) {
1236  case REF_VEHICLE_OLD: // Old vehicles we save as new ones
1237  case REF_VEHICLE: return ((const Vehicle*)obj)->index + 1;
1238  case REF_STATION: return ((const Station*)obj)->index + 1;
1239  case REF_TOWN: return ((const Town*)obj)->index + 1;
1240  case REF_ORDER: return ((const Order*)obj)->index + 1;
1241  case REF_ROADSTOPS: return ((const RoadStop*)obj)->index + 1;
1242  case REF_ENGINE_RENEWS: return ((const EngineRenew*)obj)->index + 1;
1243  case REF_CARGO_PACKET: return ((const CargoPacket*)obj)->index + 1;
1244  case REF_ORDERLIST: return ((const OrderList*)obj)->index + 1;
1245  case REF_STORAGE: return ((const PersistentStorage*)obj)->index + 1;
1246  case REF_LINK_GRAPH: return ((const LinkGraph*)obj)->index + 1;
1247  case REF_LINK_GRAPH_JOB: return ((const LinkGraphJob*)obj)->index + 1;
1248  default: NOT_REACHED();
1249  }
1250 }
1251 
1262 static void *IntToReference(size_t index, SLRefType rt)
1263 {
1264  static_assert(sizeof(size_t) <= sizeof(void *));
1265 
1266  assert(_sl.action == SLA_PTRS);
1267 
1268  /* After version 4.3 REF_VEHICLE_OLD is saved as REF_VEHICLE,
1269  * and should be loaded like that */
1270  if (rt == REF_VEHICLE_OLD && !IsSavegameVersionBefore(SLV_4, 4)) {
1271  rt = REF_VEHICLE;
1272  }
1273 
1274  /* No need to look up nullptr pointers, just return immediately */
1275  if (index == (rt == REF_VEHICLE_OLD ? 0xFFFF : 0)) return nullptr;
1276 
1277  /* Correct index. Old vehicles were saved differently:
1278  * invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
1279  if (rt != REF_VEHICLE_OLD) index--;
1280 
1281  switch (rt) {
1282  case REF_ORDERLIST:
1283  if (OrderList::IsValidID(index)) return OrderList::Get(index);
1284  SlErrorCorrupt("Referencing invalid OrderList");
1285 
1286  case REF_ORDER:
1287  if (Order::IsValidID(index)) return Order::Get(index);
1288  /* in old versions, invalid order was used to mark end of order list */
1289  if (IsSavegameVersionBefore(SLV_5, 2)) return nullptr;
1290  SlErrorCorrupt("Referencing invalid Order");
1291 
1292  case REF_VEHICLE_OLD:
1293  case REF_VEHICLE:
1294  if (Vehicle::IsValidID(index)) return Vehicle::Get(index);
1295  SlErrorCorrupt("Referencing invalid Vehicle");
1296 
1297  case REF_STATION:
1298  if (Station::IsValidID(index)) return Station::Get(index);
1299  SlErrorCorrupt("Referencing invalid Station");
1300 
1301  case REF_TOWN:
1302  if (Town::IsValidID(index)) return Town::Get(index);
1303  SlErrorCorrupt("Referencing invalid Town");
1304 
1305  case REF_ROADSTOPS:
1306  if (RoadStop::IsValidID(index)) return RoadStop::Get(index);
1307  SlErrorCorrupt("Referencing invalid RoadStop");
1308 
1309  case REF_ENGINE_RENEWS:
1310  if (EngineRenew::IsValidID(index)) return EngineRenew::Get(index);
1311  SlErrorCorrupt("Referencing invalid EngineRenew");
1312 
1313  case REF_CARGO_PACKET:
1314  if (CargoPacket::IsValidID(index)) return CargoPacket::Get(index);
1315  SlErrorCorrupt("Referencing invalid CargoPacket");
1316 
1317  case REF_STORAGE:
1318  if (PersistentStorage::IsValidID(index)) return PersistentStorage::Get(index);
1319  SlErrorCorrupt("Referencing invalid PersistentStorage");
1320 
1321  case REF_LINK_GRAPH:
1322  if (LinkGraph::IsValidID(index)) return LinkGraph::Get(index);
1323  SlErrorCorrupt("Referencing invalid LinkGraph");
1324 
1325  case REF_LINK_GRAPH_JOB:
1326  if (LinkGraphJob::IsValidID(index)) return LinkGraphJob::Get(index);
1327  SlErrorCorrupt("Referencing invalid LinkGraphJob");
1328 
1329  default: NOT_REACHED();
1330  }
1331 }
1332 
1338 void SlSaveLoadRef(void *ptr, VarType conv)
1339 {
1340  switch (_sl.action) {
1341  case SLA_SAVE:
1342  SlWriteUint32((uint32)ReferenceToInt(*(void **)ptr, (SLRefType)conv));
1343  break;
1344  case SLA_LOAD_CHECK:
1345  case SLA_LOAD:
1346  *(size_t *)ptr = IsSavegameVersionBefore(SLV_69) ? SlReadUint16() : SlReadUint32();
1347  break;
1348  case SLA_PTRS:
1349  *(void **)ptr = IntToReference(*(size_t *)ptr, (SLRefType)conv);
1350  break;
1351  case SLA_NULL:
1352  *(void **)ptr = nullptr;
1353  break;
1354  default: NOT_REACHED();
1355  }
1356 }
1357 
1361 template <template<typename, typename> typename Tstorage, typename Tvar, typename Tallocator = std::allocator<Tvar>>
1363  typedef Tstorage<Tvar, Tallocator> SlStorageT;
1364 public:
1371  static size_t SlCalcLen(const void *storage, VarType conv, SaveLoadType cmd = SL_VAR)
1372  {
1373  assert(cmd == SL_VAR || cmd == SL_REF);
1374 
1375  const SlStorageT *list = static_cast<const SlStorageT *>(storage);
1376 
1377  int type_size = SlGetArrayLength(list->size());
1378  int item_size = SlCalcConvFileLen(cmd == SL_VAR ? conv : (VarType)SLE_FILE_U32);
1379  return list->size() * item_size + type_size;
1380  }
1381 
1382  static void SlSaveLoadMember(SaveLoadType cmd, Tvar *item, VarType conv)
1383  {
1384  switch (cmd) {
1385  case SL_VAR: SlSaveLoadConv(item, conv); break;
1386  case SL_REF: SlSaveLoadRef(item, conv); break;
1387  default:
1388  NOT_REACHED();
1389  }
1390  }
1391 
1398  static void SlSaveLoad(void *storage, VarType conv, SaveLoadType cmd = SL_VAR)
1399  {
1400  assert(cmd == SL_VAR || cmd == SL_REF);
1401 
1402  SlStorageT *list = static_cast<SlStorageT *>(storage);
1403 
1404  switch (_sl.action) {
1405  case SLA_SAVE:
1406  SlWriteArrayLength(list->size());
1407 
1408  for (auto &item : *list) {
1409  SlSaveLoadMember(cmd, &item, conv);
1410  }
1411  break;
1412 
1413  case SLA_LOAD_CHECK:
1414  case SLA_LOAD: {
1415  size_t length;
1416  switch (cmd) {
1417  case SL_VAR: length = IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? SlReadUint32() : SlReadArrayLength(); break;
1418  case SL_REF: length = IsSavegameVersionBefore(SLV_69) ? SlReadUint16() : IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? SlReadUint32() : SlReadArrayLength(); break;
1419  default: NOT_REACHED();
1420  }
1421 
1422  /* Load each value and push to the end of the storage. */
1423  for (size_t i = 0; i < length; i++) {
1424  Tvar &data = list->emplace_back();
1425  SlSaveLoadMember(cmd, &data, conv);
1426  }
1427  break;
1428  }
1429 
1430  case SLA_PTRS:
1431  for (auto &item : *list) {
1432  SlSaveLoadMember(cmd, &item, conv);
1433  }
1434  break;
1435 
1436  case SLA_NULL:
1437  list->clear();
1438  break;
1439 
1440  default: NOT_REACHED();
1441  }
1442  }
1443 };
1444 
1450 static inline size_t SlCalcRefListLen(const void *list, VarType conv)
1451 {
1453 }
1454 
1460 static void SlRefList(void *list, VarType conv)
1461 {
1462  /* Automatically calculate the length? */
1463  if (_sl.need_length != NL_NONE) {
1464  SlSetLength(SlCalcRefListLen(list, conv));
1465  /* Determine length only? */
1466  if (_sl.need_length == NL_CALCLENGTH) return;
1467  }
1468 
1470 }
1471 
1477 static inline size_t SlCalcDequeLen(const void *deque, VarType conv)
1478 {
1479  switch (GetVarMemType(conv)) {
1480  case SLE_VAR_BL: return SlStorageHelper<std::deque, bool>::SlCalcLen(deque, conv);
1481  case SLE_VAR_I8: return SlStorageHelper<std::deque, int8>::SlCalcLen(deque, conv);
1482  case SLE_VAR_U8: return SlStorageHelper<std::deque, uint8>::SlCalcLen(deque, conv);
1483  case SLE_VAR_I16: return SlStorageHelper<std::deque, int16>::SlCalcLen(deque, conv);
1484  case SLE_VAR_U16: return SlStorageHelper<std::deque, uint16>::SlCalcLen(deque, conv);
1485  case SLE_VAR_I32: return SlStorageHelper<std::deque, int32>::SlCalcLen(deque, conv);
1486  case SLE_VAR_U32: return SlStorageHelper<std::deque, uint32>::SlCalcLen(deque, conv);
1487  case SLE_VAR_I64: return SlStorageHelper<std::deque, int64>::SlCalcLen(deque, conv);
1488  case SLE_VAR_U64: return SlStorageHelper<std::deque, uint64>::SlCalcLen(deque, conv);
1489  default: NOT_REACHED();
1490  }
1491 }
1492 
1498 static void SlDeque(void *deque, VarType conv)
1499 {
1500  switch (GetVarMemType(conv)) {
1501  case SLE_VAR_BL: SlStorageHelper<std::deque, bool>::SlSaveLoad(deque, conv); break;
1502  case SLE_VAR_I8: SlStorageHelper<std::deque, int8>::SlSaveLoad(deque, conv); break;
1503  case SLE_VAR_U8: SlStorageHelper<std::deque, uint8>::SlSaveLoad(deque, conv); break;
1504  case SLE_VAR_I16: SlStorageHelper<std::deque, int16>::SlSaveLoad(deque, conv); break;
1505  case SLE_VAR_U16: SlStorageHelper<std::deque, uint16>::SlSaveLoad(deque, conv); break;
1506  case SLE_VAR_I32: SlStorageHelper<std::deque, int32>::SlSaveLoad(deque, conv); break;
1507  case SLE_VAR_U32: SlStorageHelper<std::deque, uint32>::SlSaveLoad(deque, conv); break;
1508  case SLE_VAR_I64: SlStorageHelper<std::deque, int64>::SlSaveLoad(deque, conv); break;
1509  case SLE_VAR_U64: SlStorageHelper<std::deque, uint64>::SlSaveLoad(deque, conv); break;
1510  default: NOT_REACHED();
1511  }
1512 }
1513 
1519 static inline size_t SlCalcVectorLen(const void *vector, VarType conv)
1520 {
1521  switch (GetVarMemType(conv)) {
1522  case SLE_VAR_BL: NOT_REACHED(); // Not supported
1523  case SLE_VAR_I8: return SlStorageHelper<std::vector, int8>::SlCalcLen(vector, conv);
1524  case SLE_VAR_U8: return SlStorageHelper<std::vector, uint8>::SlCalcLen(vector, conv);
1525  case SLE_VAR_I16: return SlStorageHelper<std::vector, int16>::SlCalcLen(vector, conv);
1526  case SLE_VAR_U16: return SlStorageHelper<std::vector, uint16>::SlCalcLen(vector, conv);
1527  case SLE_VAR_I32: return SlStorageHelper<std::vector, int32>::SlCalcLen(vector, conv);
1528  case SLE_VAR_U32: return SlStorageHelper<std::vector, uint32>::SlCalcLen(vector, conv);
1529  case SLE_VAR_I64: return SlStorageHelper<std::vector, int64>::SlCalcLen(vector, conv);
1530  case SLE_VAR_U64: return SlStorageHelper<std::vector, uint64>::SlCalcLen(vector, conv);
1531  default: NOT_REACHED();
1532  }
1533 }
1534 
1540 static void SlVector(void *vector, VarType conv)
1541 {
1542  switch (GetVarMemType(conv)) {
1543  case SLE_VAR_BL: NOT_REACHED(); // Not supported
1544  case SLE_VAR_I8: SlStorageHelper<std::vector, int8>::SlSaveLoad(vector, conv); break;
1545  case SLE_VAR_U8: SlStorageHelper<std::vector, uint8>::SlSaveLoad(vector, conv); break;
1546  case SLE_VAR_I16: SlStorageHelper<std::vector, int16>::SlSaveLoad(vector, conv); break;
1547  case SLE_VAR_U16: SlStorageHelper<std::vector, uint16>::SlSaveLoad(vector, conv); break;
1548  case SLE_VAR_I32: SlStorageHelper<std::vector, int32>::SlSaveLoad(vector, conv); break;
1549  case SLE_VAR_U32: SlStorageHelper<std::vector, uint32>::SlSaveLoad(vector, conv); break;
1550  case SLE_VAR_I64: SlStorageHelper<std::vector, int64>::SlSaveLoad(vector, conv); break;
1551  case SLE_VAR_U64: SlStorageHelper<std::vector, uint64>::SlSaveLoad(vector, conv); break;
1552  default: NOT_REACHED();
1553  }
1554 }
1555 
1557 static inline bool SlIsObjectValidInSavegame(const SaveLoad &sld)
1558 {
1559  return (_sl_version >= sld.version_from && _sl_version < sld.version_to);
1560 }
1561 
1567 static size_t SlCalcTableHeader(const SaveLoadTable &slt)
1568 {
1569  size_t length = 0;
1570 
1571  for (auto &sld : slt) {
1572  if (!SlIsObjectValidInSavegame(sld)) continue;
1573 
1574  length += SlCalcConvFileLen(SLE_UINT8);
1575  length += SlCalcStdStringLen(&sld.name);
1576  }
1577 
1578  length += SlCalcConvFileLen(SLE_UINT8); // End-of-list entry.
1579 
1580  for (auto &sld : slt) {
1581  if (!SlIsObjectValidInSavegame(sld)) continue;
1582  if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1583  length += SlCalcTableHeader(sld.handler->GetDescription());
1584  }
1585  }
1586 
1587  return length;
1588 }
1589 
1596 size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt)
1597 {
1598  size_t length = 0;
1599 
1600  /* Need to determine the length and write a length tag. */
1601  for (auto &sld : slt) {
1602  length += SlCalcObjMemberLength(object, sld);
1603  }
1604  return length;
1605 }
1606 
1607 size_t SlCalcObjMemberLength(const void *object, const SaveLoad &sld)
1608 {
1609  assert(_sl.action == SLA_SAVE);
1610 
1611  if (!SlIsObjectValidInSavegame(sld)) return 0;
1612 
1613  switch (sld.cmd) {
1614  case SL_VAR: return SlCalcConvFileLen(sld.conv);
1615  case SL_REF: return SlCalcRefLen();
1616  case SL_ARR: return SlCalcArrayLen(sld.length, sld.conv);
1617  case SL_STR: return SlCalcStringLen(GetVariableAddress(object, sld), sld.length, sld.conv);
1618  case SL_REFLIST: return SlCalcRefListLen(GetVariableAddress(object, sld), sld.conv);
1619  case SL_DEQUE: return SlCalcDequeLen(GetVariableAddress(object, sld), sld.conv);
1620  case SL_VECTOR: return SlCalcVectorLen(GetVariableAddress(object, sld), sld.conv);
1621  case SL_STDSTR: return SlCalcStdStringLen(GetVariableAddress(object, sld));
1622  case SL_SAVEBYTE: return 1; // a byte is logically of size 1
1623  case SL_NULL: return SlCalcConvFileLen(sld.conv) * sld.length;
1624 
1625  case SL_STRUCT:
1626  case SL_STRUCTLIST: {
1627  NeedLength old_need_length = _sl.need_length;
1628  size_t old_obj_len = _sl.obj_len;
1629 
1631  _sl.obj_len = 0;
1632 
1633  /* Pretend that we are saving to collect the object size. Other
1634  * means are difficult, as we don't know the length of the list we
1635  * are about to store. */
1636  sld.handler->Save(const_cast<void *>(object));
1637  size_t length = _sl.obj_len;
1638 
1639  _sl.obj_len = old_obj_len;
1640  _sl.need_length = old_need_length;
1641 
1642  if (sld.cmd == SL_STRUCT) {
1643  length += SlGetArrayLength(1);
1644  }
1645 
1646  return length;
1647  }
1648 
1649  default: NOT_REACHED();
1650  }
1651  return 0;
1652 }
1653 
1659 [[maybe_unused]] static bool IsVariableSizeRight(const SaveLoad &sld)
1660 {
1661  if (GetVarMemType(sld.conv) == SLE_VAR_NULL) return true;
1662 
1663  switch (sld.cmd) {
1664  case SL_VAR:
1665  switch (GetVarMemType(sld.conv)) {
1666  case SLE_VAR_BL:
1667  return sld.size == sizeof(bool);
1668  case SLE_VAR_I8:
1669  case SLE_VAR_U8:
1670  return sld.size == sizeof(int8);
1671  case SLE_VAR_I16:
1672  case SLE_VAR_U16:
1673  return sld.size == sizeof(int16);
1674  case SLE_VAR_I32:
1675  case SLE_VAR_U32:
1676  return sld.size == sizeof(int32);
1677  case SLE_VAR_I64:
1678  case SLE_VAR_U64:
1679  return sld.size == sizeof(int64);
1680  case SLE_VAR_NAME:
1681  return sld.size == sizeof(std::string);
1682  default:
1683  return sld.size == sizeof(void *);
1684  }
1685  case SL_REF:
1686  /* These should all be pointer sized. */
1687  return sld.size == sizeof(void *);
1688 
1689  case SL_STR:
1690  /* These should be pointer sized, or fixed array. */
1691  return sld.size == sizeof(void *) || sld.size == sld.length;
1692 
1693  case SL_STDSTR:
1694  /* These should be all pointers to std::string. */
1695  return sld.size == sizeof(std::string);
1696 
1697  default:
1698  return true;
1699  }
1700 }
1701 
1702 static bool SlObjectMember(void *object, const SaveLoad &sld)
1703 {
1704  assert(IsVariableSizeRight(sld));
1705 
1706  if (!SlIsObjectValidInSavegame(sld)) return false;
1707 
1708  VarType conv = GB(sld.conv, 0, 8);
1709  switch (sld.cmd) {
1710  case SL_VAR:
1711  case SL_REF:
1712  case SL_ARR:
1713  case SL_STR:
1714  case SL_REFLIST:
1715  case SL_DEQUE:
1716  case SL_VECTOR:
1717  case SL_STDSTR: {
1718  void *ptr = GetVariableAddress(object, sld);
1719 
1720  switch (sld.cmd) {
1721  case SL_VAR: SlSaveLoadConv(ptr, conv); break;
1722  case SL_REF: SlSaveLoadRef(ptr, conv); break;
1723  case SL_ARR: SlArray(ptr, sld.length, conv); break;
1724  case SL_STR: SlString(ptr, sld.length, sld.conv); break;
1725  case SL_REFLIST: SlRefList(ptr, conv); break;
1726  case SL_DEQUE: SlDeque(ptr, conv); break;
1727  case SL_VECTOR: SlVector(ptr, conv); break;
1728  case SL_STDSTR: SlStdString(ptr, sld.conv); break;
1729  default: NOT_REACHED();
1730  }
1731  break;
1732  }
1733 
1734  /* SL_SAVEBYTE writes a value to the savegame to identify the type of an object.
1735  * When loading, the value is read explicitly with SlReadByte() to determine which
1736  * object description to use. */
1737  case SL_SAVEBYTE: {
1738  void *ptr = GetVariableAddress(object, sld);
1739 
1740  switch (_sl.action) {
1741  case SLA_SAVE: SlWriteByte(*(uint8 *)ptr); break;
1742  case SLA_LOAD_CHECK:
1743  case SLA_LOAD:
1744  case SLA_PTRS:
1745  case SLA_NULL: break;
1746  default: NOT_REACHED();
1747  }
1748  break;
1749  }
1750 
1751  case SL_NULL: {
1752  assert(GetVarMemType(sld.conv) == SLE_VAR_NULL);
1753 
1754  switch (_sl.action) {
1755  case SLA_LOAD_CHECK:
1756  case SLA_LOAD: SlSkipBytes(SlCalcConvFileLen(sld.conv) * sld.length); break;
1757  case SLA_SAVE: for (int i = 0; i < SlCalcConvFileLen(sld.conv) * sld.length; i++) SlWriteByte(0); break;
1758  case SLA_PTRS:
1759  case SLA_NULL: break;
1760  default: NOT_REACHED();
1761  }
1762  break;
1763  }
1764 
1765  case SL_STRUCT:
1766  case SL_STRUCTLIST:
1767  switch (_sl.action) {
1768  case SLA_SAVE: {
1769  if (sld.cmd == SL_STRUCT) {
1770  /* Store in the savegame if this struct was written or not. */
1771  SlSetStructListLength(SlCalcObjMemberLength(object, sld) > SlGetArrayLength(1) ? 1 : 0);
1772  }
1773  sld.handler->Save(object);
1774  break;
1775  }
1776 
1777  case SLA_LOAD_CHECK: {
1780  }
1781  sld.handler->LoadCheck(object);
1782  break;
1783  }
1784 
1785  case SLA_LOAD: {
1788  }
1789  sld.handler->Load(object);
1790  break;
1791  }
1792 
1793  case SLA_PTRS:
1794  sld.handler->FixPointers(object);
1795  break;
1796 
1797  case SLA_NULL: break;
1798  default: NOT_REACHED();
1799  }
1800  break;
1801 
1802  default: NOT_REACHED();
1803  }
1804  return true;
1805 }
1806 
1811 void SlSetStructListLength(size_t length)
1812 {
1813  /* Automatically calculate the length? */
1814  if (_sl.need_length != NL_NONE) {
1815  SlSetLength(SlGetArrayLength(length));
1816  if (_sl.need_length == NL_CALCLENGTH) return;
1817  }
1818 
1819  SlWriteArrayLength(length);
1820 }
1821 
1827 size_t SlGetStructListLength(size_t limit)
1828 {
1829  size_t length = SlReadArrayLength();
1830  if (length > limit) SlErrorCorrupt("List exceeds storage size");
1831 
1832  return length;
1833 }
1834 
1840 void SlObject(void *object, const SaveLoadTable &slt)
1841 {
1842  /* Automatically calculate the length? */
1843  if (_sl.need_length != NL_NONE) {
1844  SlSetLength(SlCalcObjLength(object, slt));
1845  if (_sl.need_length == NL_CALCLENGTH) return;
1846  }
1847 
1848  for (auto &sld : slt) {
1849  SlObjectMember(object, sld);
1850  }
1851 }
1852 
1858  void Save(void *object) const override
1859  {
1860  NOT_REACHED();
1861  }
1862 
1863  void Load(void *object) const override
1864  {
1865  size_t length = SlGetStructListLength(UINT32_MAX);
1866  for (; length > 0; length--) {
1867  SlObject(object, this->GetLoadDescription());
1868  }
1869  }
1870 
1871  void LoadCheck(void *object) const override
1872  {
1873  this->Load(object);
1874  }
1875 
1876  virtual SaveLoadTable GetDescription() const override
1877  {
1878  return {};
1879  }
1880 
1882  {
1883  NOT_REACHED();
1884  }
1885 };
1886 
1893 std::vector<SaveLoad> SlTableHeader(const SaveLoadTable &slt)
1894 {
1895  /* You can only use SlTableHeader if you are a CH_TABLE. */
1896  assert(_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
1897 
1898  switch (_sl.action) {
1899  case SLA_LOAD_CHECK:
1900  case SLA_LOAD: {
1901  std::vector<SaveLoad> saveloads;
1902 
1903  /* Build a key lookup mapping based on the available fields. */
1904  std::map<std::string, const SaveLoad *> key_lookup;
1905  for (auto &sld : slt) {
1906  if (!SlIsObjectValidInSavegame(sld)) continue;
1907 
1908  /* Check that there is only one active SaveLoad for a given name. */
1909  assert(key_lookup.find(sld.name) == key_lookup.end());
1910  key_lookup[sld.name] = &sld;
1911  }
1912 
1913  while (true) {
1914  uint8 type;
1915  SlSaveLoadConv(&type, SLE_UINT8);
1916  if (type == SLE_FILE_END) break;
1917 
1918  std::string key;
1919  SlStdString(&key, SLE_STR);
1920 
1921  auto sld_it = key_lookup.find(key);
1922  if (sld_it == key_lookup.end()) {
1923  /* SLA_LOADCHECK triggers this debug statement a lot and is perfectly normal. */
1924  Debug(sl, _sl.action == SLA_LOAD ? 2 : 6, "Field '{}' of type 0x{:02x} not found, skipping", key, type);
1925 
1926  std::shared_ptr<SaveLoadHandler> handler = nullptr;
1927  SaveLoadType slt;
1928  switch (type & SLE_FILE_TYPE_MASK) {
1929  case SLE_FILE_STRING:
1930  /* Strings are always marked with SLE_FILE_HAS_LENGTH_FIELD, as they are a list of chars. */
1931  slt = SL_STR;
1932  break;
1933 
1934  case SLE_FILE_STRUCT:
1935  /* Structs are always marked with SLE_FILE_HAS_LENGTH_FIELD as SL_STRUCT is seen as a list of 0/1 in length. */
1936  slt = SL_STRUCTLIST;
1937  handler = std::make_shared<SlSkipHandler>();
1938  break;
1939 
1940  default:
1941  slt = (type & SLE_FILE_HAS_LENGTH_FIELD) ? SL_ARR : SL_VAR;
1942  break;
1943  }
1944 
1945  /* We don't know this field, so read to nothing. */
1946  saveloads.push_back({key, slt, ((VarType)type & SLE_FILE_TYPE_MASK) | SLE_VAR_NULL, 1, SL_MIN_VERSION, SL_MAX_VERSION, 0, nullptr, 0, handler});
1947  continue;
1948  }
1949 
1950  /* Validate the type of the field. If it is changed, the
1951  * savegame should have been bumped so we know how to do the
1952  * conversion. If this error triggers, that clearly didn't
1953  * happen and this is a friendly poke to the developer to bump
1954  * the savegame version and add conversion code. */
1955  uint8 correct_type = GetSavegameFileType(*sld_it->second);
1956  if (correct_type != type) {
1957  Debug(sl, 1, "Field type for '{}' was expected to be 0x{:02x} but 0x{:02x} was found", key, correct_type, type);
1958  SlErrorCorrupt("Field type is different than expected");
1959  }
1960  saveloads.push_back(*sld_it->second);
1961  }
1962 
1963  for (auto &sld : saveloads) {
1964  if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1965  sld.handler->load_description = SlTableHeader(sld.handler->GetDescription());
1966  }
1967  }
1968 
1969  return saveloads;
1970  }
1971 
1972  case SLA_SAVE: {
1973  /* Automatically calculate the length? */
1974  if (_sl.need_length != NL_NONE) {
1976  if (_sl.need_length == NL_CALCLENGTH) break;
1977  }
1978 
1979  for (auto &sld : slt) {
1980  if (!SlIsObjectValidInSavegame(sld)) continue;
1981  /* Make sure we are not storing empty keys. */
1982  assert(!sld.name.empty());
1983 
1984  uint8 type = GetSavegameFileType(sld);
1985  assert(type != SLE_FILE_END);
1986 
1987  SlSaveLoadConv(&type, SLE_UINT8);
1988  SlStdString(const_cast<std::string *>(&sld.name), SLE_STR);
1989  }
1990 
1991  /* Add an end-of-header marker. */
1992  uint8 type = SLE_FILE_END;
1993  SlSaveLoadConv(&type, SLE_UINT8);
1994 
1995  /* After the table, write down any sub-tables we might have. */
1996  for (auto &sld : slt) {
1997  if (!SlIsObjectValidInSavegame(sld)) continue;
1998  if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1999  /* SlCalcTableHeader already looks in sub-lists, so avoid the length being added twice. */
2000  NeedLength old_need_length = _sl.need_length;
2002 
2003  SlTableHeader(sld.handler->GetDescription());
2004 
2005  _sl.need_length = old_need_length;
2006  }
2007  }
2008 
2009  break;
2010  }
2011 
2012  default: NOT_REACHED();
2013  }
2014 
2015  return std::vector<SaveLoad>();
2016 }
2017 
2031 std::vector<SaveLoad> SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
2032 {
2033  assert(_sl.action == SLA_LOAD || _sl.action == SLA_LOAD_CHECK);
2034  /* CH_TABLE / CH_SPARSE_TABLE always have a header. */
2035  if (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE) return SlTableHeader(slt);
2036 
2037  std::vector<SaveLoad> saveloads;
2038 
2039  /* Build a key lookup mapping based on the available fields. */
2040  std::map<std::string, std::vector<const SaveLoad *>> key_lookup;
2041  for (auto &sld : slt) {
2042  /* All entries should have a name; otherwise the entry should just be removed. */
2043  assert(!sld.name.empty());
2044 
2045  key_lookup[sld.name].push_back(&sld);
2046  }
2047 
2048  for (auto &slc : slct) {
2049  if (slc.name.empty()) {
2050  /* In old savegames there can be data we no longer care for. We
2051  * skip this by simply reading the amount of bytes indicated and
2052  * send those to /dev/null. */
2053  saveloads.push_back({"", SL_NULL, SLE_FILE_U8 | SLE_VAR_NULL, slc.length, slc.version_from, slc.version_to, 0, nullptr, 0, nullptr});
2054  } else {
2055  auto sld_it = key_lookup.find(slc.name);
2056  /* If this branch triggers, it means that an entry in the
2057  * SaveLoadCompat list is not mentioned in the SaveLoad list. Did
2058  * you rename a field in one and not in the other? */
2059  if (sld_it == key_lookup.end()) {
2060  /* This isn't an assert, as that leaves no information what
2061  * field was to blame. This way at least we have breadcrumbs. */
2062  Debug(sl, 0, "internal error: saveload compatibility field '{}' not found", slc.name);
2063  SlErrorCorrupt("Internal error with savegame compatibility");
2064  }
2065  for (auto &sld : sld_it->second) {
2066  saveloads.push_back(*sld);
2067  }
2068  }
2069  }
2070 
2071  for (auto &sld : saveloads) {
2072  if (!SlIsObjectValidInSavegame(sld)) continue;
2073  if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
2074  sld.handler->load_description = SlCompatTableHeader(sld.handler->GetDescription(), sld.handler->GetCompatDescription());
2075  }
2076  }
2077 
2078  return saveloads;
2079 }
2080 
2085 void SlGlobList(const SaveLoadTable &slt)
2086 {
2087  SlObject(nullptr, slt);
2088 }
2089 
2095 void SlAutolength(AutolengthProc *proc, void *arg)
2096 {
2097  size_t offs;
2098 
2099  assert(_sl.action == SLA_SAVE);
2100 
2101  /* Tell it to calculate the length */
2103  _sl.obj_len = 0;
2104  proc(arg);
2105 
2106  /* Setup length */
2109 
2110  offs = _sl.dumper->GetSize() + _sl.obj_len;
2111 
2112  /* And write the stuff */
2113  proc(arg);
2114 
2115  if (offs != _sl.dumper->GetSize()) SlErrorCorrupt("Invalid chunk size");
2116 }
2117 
2118 void ChunkHandler::LoadCheck(size_t len) const
2119 {
2120  switch (_sl.block_mode) {
2121  case CH_TABLE:
2122  case CH_SPARSE_TABLE:
2123  SlTableHeader({});
2124  FALLTHROUGH;
2125  case CH_ARRAY:
2126  case CH_SPARSE_ARRAY:
2127  SlSkipArray();
2128  break;
2129  case CH_RIFF:
2130  SlSkipBytes(len);
2131  break;
2132  default:
2133  NOT_REACHED();
2134  }
2135 }
2136 
2141 static void SlLoadChunk(const ChunkHandler &ch)
2142 {
2143  byte m = SlReadByte();
2144  size_t len;
2145  size_t endoffs;
2146 
2147  _sl.block_mode = m & CH_TYPE_MASK;
2148  _sl.obj_len = 0;
2149  _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
2150 
2151  /* The header should always be at the start. Read the length; the
2152  * Load() should as first action process the header. */
2153  if (_sl.expect_table_header) {
2154  SlIterateArray();
2155  }
2156 
2157  switch (_sl.block_mode) {
2158  case CH_TABLE:
2159  case CH_ARRAY:
2160  _sl.array_index = 0;
2161  ch.Load();
2162  if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
2163  break;
2164  case CH_SPARSE_TABLE:
2165  case CH_SPARSE_ARRAY:
2166  ch.Load();
2167  if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
2168  break;
2169  case CH_RIFF:
2170  /* Read length */
2171  len = (SlReadByte() << 16) | ((m >> 4) << 24);
2172  len += SlReadUint16();
2173  _sl.obj_len = len;
2174  endoffs = _sl.reader->GetSize() + len;
2175  ch.Load();
2176  if (_sl.reader->GetSize() != endoffs) SlErrorCorrupt("Invalid chunk size");
2177  break;
2178  default:
2179  SlErrorCorrupt("Invalid chunk type");
2180  break;
2181  }
2182 
2183  if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2184 }
2185 
2191 static void SlLoadCheckChunk(const ChunkHandler &ch)
2192 {
2193  byte m = SlReadByte();
2194  size_t len;
2195  size_t endoffs;
2196 
2197  _sl.block_mode = m & CH_TYPE_MASK;
2198  _sl.obj_len = 0;
2199  _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
2200 
2201  /* The header should always be at the start. Read the length; the
2202  * LoadCheck() should as first action process the header. */
2203  if (_sl.expect_table_header) {
2204  SlIterateArray();
2205  }
2206 
2207  switch (_sl.block_mode) {
2208  case CH_TABLE:
2209  case CH_ARRAY:
2210  _sl.array_index = 0;
2211  ch.LoadCheck();
2212  break;
2213  case CH_SPARSE_TABLE:
2214  case CH_SPARSE_ARRAY:
2215  ch.LoadCheck();
2216  break;
2217  case CH_RIFF:
2218  /* Read length */
2219  len = (SlReadByte() << 16) | ((m >> 4) << 24);
2220  len += SlReadUint16();
2221  _sl.obj_len = len;
2222  endoffs = _sl.reader->GetSize() + len;
2223  ch.LoadCheck(len);
2224  if (_sl.reader->GetSize() != endoffs) SlErrorCorrupt("Invalid chunk size");
2225  break;
2226  default:
2227  SlErrorCorrupt("Invalid chunk type");
2228  break;
2229  }
2230 
2231  if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2232 }
2233 
2239 static void SlSaveChunk(const ChunkHandler &ch)
2240 {
2241  if (ch.type == CH_READONLY) return;
2242 
2243  SlWriteUint32(ch.id);
2244  Debug(sl, 2, "Saving chunk {:c}{:c}{:c}{:c}", ch.id >> 24, ch.id >> 16, ch.id >> 8, ch.id);
2245 
2246  _sl.block_mode = ch.type;
2247  _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
2248 
2250 
2251  switch (_sl.block_mode) {
2252  case CH_RIFF:
2253  ch.Save();
2254  break;
2255  case CH_TABLE:
2256  case CH_ARRAY:
2257  _sl.last_array_index = 0;
2259  ch.Save();
2260  SlWriteArrayLength(0); // Terminate arrays
2261  break;
2262  case CH_SPARSE_TABLE:
2263  case CH_SPARSE_ARRAY:
2265  ch.Save();
2266  SlWriteArrayLength(0); // Terminate arrays
2267  break;
2268  default: NOT_REACHED();
2269  }
2270 
2271  if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2272 }
2273 
2275 static void SlSaveChunks()
2276 {
2277  for (auto &ch : ChunkHandlers()) {
2278  SlSaveChunk(ch);
2279  }
2280 
2281  /* Terminator */
2282  SlWriteUint32(0);
2283 }
2284 
2291 static const ChunkHandler *SlFindChunkHandler(uint32 id)
2292 {
2293  for (const ChunkHandler &ch : ChunkHandlers()) if (ch.id == id) return &ch;
2294  return nullptr;
2295 }
2296 
2298 static void SlLoadChunks()
2299 {
2300  uint32 id;
2301  const ChunkHandler *ch;
2302 
2303  for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
2304  Debug(sl, 2, "Loading chunk {:c}{:c}{:c}{:c}", id >> 24, id >> 16, id >> 8, id);
2305 
2306  ch = SlFindChunkHandler(id);
2307  if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2308  SlLoadChunk(*ch);
2309  }
2310 }
2311 
2313 static void SlLoadCheckChunks()
2314 {
2315  uint32 id;
2316  const ChunkHandler *ch;
2317 
2318  for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
2319  Debug(sl, 2, "Loading chunk {:c}{:c}{:c}{:c}", id >> 24, id >> 16, id >> 8, id);
2320 
2321  ch = SlFindChunkHandler(id);
2322  if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2323  SlLoadCheckChunk(*ch);
2324  }
2325 }
2326 
2328 static void SlFixPointers()
2329 {
2330  _sl.action = SLA_PTRS;
2331 
2332  for (const ChunkHandler &ch : ChunkHandlers()) {
2333  Debug(sl, 3, "Fixing pointers for {:c}{:c}{:c}{:c}", ch.id >> 24, ch.id >> 16, ch.id >> 8, ch.id);
2334  ch.FixPointers();
2335  }
2336 
2337  assert(_sl.action == SLA_PTRS);
2338 }
2339 
2340 
2343  FILE *file;
2344  long begin;
2345 
2350  FileReader(FILE *file) : LoadFilter(nullptr), file(file), begin(ftell(file))
2351  {
2352  }
2353 
2356  {
2357  if (this->file != nullptr) fclose(this->file);
2358  this->file = nullptr;
2359 
2360  /* Make sure we don't double free. */
2361  _sl.sf = nullptr;
2362  }
2363 
2364  size_t Read(byte *buf, size_t size) override
2365  {
2366  /* We're in the process of shutting down, i.e. in "failure" mode. */
2367  if (this->file == nullptr) return 0;
2368 
2369  return fread(buf, 1, size, this->file);
2370  }
2371 
2372  void Reset() override
2373  {
2374  clearerr(this->file);
2375  if (fseek(this->file, this->begin, SEEK_SET)) {
2376  Debug(sl, 1, "Could not reset the file reading");
2377  }
2378  }
2379 };
2380 
2383  FILE *file;
2384 
2389  FileWriter(FILE *file) : SaveFilter(nullptr), file(file)
2390  {
2391  }
2392 
2395  {
2396  this->Finish();
2397 
2398  /* Make sure we don't double free. */
2399  _sl.sf = nullptr;
2400  }
2401 
2402  void Write(byte *buf, size_t size) override
2403  {
2404  /* We're in the process of shutting down, i.e. in "failure" mode. */
2405  if (this->file == nullptr) return;
2406 
2407  if (fwrite(buf, 1, size, this->file) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
2408  }
2409 
2410  void Finish() override
2411  {
2412  if (this->file != nullptr) fclose(this->file);
2413  this->file = nullptr;
2414  }
2415 };
2416 
2417 /*******************************************
2418  ********** START OF LZO CODE **************
2419  *******************************************/
2420 
2421 #ifdef WITH_LZO
2422 #include <lzo/lzo1x.h>
2423 
2425 static const uint LZO_BUFFER_SIZE = 8192;
2426 
2434  {
2435  if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2436  }
2437 
2438  size_t Read(byte *buf, size_t ssize) override
2439  {
2440  assert(ssize >= LZO_BUFFER_SIZE);
2441 
2442  /* Buffer size is from the LZO docs plus the chunk header size. */
2443  byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32) * 2];
2444  uint32 tmp[2];
2445  uint32 size;
2446  lzo_uint len = ssize;
2447 
2448  /* Read header*/
2449  if (this->chain->Read((byte*)tmp, sizeof(tmp)) != sizeof(tmp)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed");
2450 
2451  /* Check if size is bad */
2452  ((uint32*)out)[0] = size = tmp[1];
2453 
2454  if (_sl_version != SL_MIN_VERSION) {
2455  tmp[0] = TO_BE32(tmp[0]);
2456  size = TO_BE32(size);
2457  }
2458 
2459  if (size >= sizeof(out)) SlErrorCorrupt("Inconsistent size");
2460 
2461  /* Read block */
2462  if (this->chain->Read(out + sizeof(uint32), size) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2463 
2464  /* Verify checksum */
2465  if (tmp[0] != lzo_adler32(0, out, size + sizeof(uint32))) SlErrorCorrupt("Bad checksum");
2466 
2467  /* Decompress */
2468  int ret = lzo1x_decompress_safe(out + sizeof(uint32) * 1, size, buf, &len, nullptr);
2469  if (ret != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2470  return len;
2471  }
2472 };
2473 
2481  LZOSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2482  {
2483  if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2484  }
2485 
2486  void Write(byte *buf, size_t size) override
2487  {
2488  const lzo_bytep in = buf;
2489  /* Buffer size is from the LZO docs plus the chunk header size. */
2490  byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32) * 2];
2491  byte wrkmem[LZO1X_1_MEM_COMPRESS];
2492  lzo_uint outlen;
2493 
2494  do {
2495  /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2496  lzo_uint len = size > LZO_BUFFER_SIZE ? LZO_BUFFER_SIZE : (lzo_uint)size;
2497  lzo1x_1_compress(in, len, out + sizeof(uint32) * 2, &outlen, wrkmem);
2498  ((uint32*)out)[1] = TO_BE32((uint32)outlen);
2499  ((uint32*)out)[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32), outlen + sizeof(uint32)));
2500  this->chain->Write(out, outlen + sizeof(uint32) * 2);
2501 
2502  /* Move to next data chunk. */
2503  size -= len;
2504  in += len;
2505  } while (size > 0);
2506  }
2507 };
2508 
2509 #endif /* WITH_LZO */
2510 
2511 /*********************************************
2512  ******** START OF NOCOMP CODE (uncompressed)*
2513  *********************************************/
2514 
2522  {
2523  }
2524 
2525  size_t Read(byte *buf, size_t size) override
2526  {
2527  return this->chain->Read(buf, size);
2528  }
2529 };
2530 
2538  NoCompSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2539  {
2540  }
2541 
2542  void Write(byte *buf, size_t size) override
2543  {
2544  this->chain->Write(buf, size);
2545  }
2546 };
2547 
2548 /********************************************
2549  ********** START OF ZLIB CODE **************
2550  ********************************************/
2551 
2552 #if defined(WITH_ZLIB)
2553 #include <zlib.h>
2554 
2557  z_stream z;
2565  {
2566  memset(&this->z, 0, sizeof(this->z));
2567  if (inflateInit(&this->z) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2568  }
2569 
2571  ~ZlibLoadFilter()
2572  {
2573  inflateEnd(&this->z);
2574  }
2575 
2576  size_t Read(byte *buf, size_t size) override
2577  {
2578  this->z.next_out = buf;
2579  this->z.avail_out = (uint)size;
2580 
2581  do {
2582  /* read more bytes from the file? */
2583  if (this->z.avail_in == 0) {
2584  this->z.next_in = this->fread_buf;
2585  this->z.avail_in = (uint)this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2586  }
2587 
2588  /* inflate the data */
2589  int r = inflate(&this->z, 0);
2590  if (r == Z_STREAM_END) break;
2591 
2592  if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "inflate() failed");
2593  } while (this->z.avail_out != 0);
2594 
2595  return size - this->z.avail_out;
2596  }
2597 };
2598 
2601  z_stream z;
2602 
2608  ZlibSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2609  {
2610  memset(&this->z, 0, sizeof(this->z));
2611  if (deflateInit(&this->z, compression_level) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2612  }
2613 
2616  {
2617  deflateEnd(&this->z);
2618  }
2619 
2626  void WriteLoop(byte *p, size_t len, int mode)
2627  {
2628  byte buf[MEMORY_CHUNK_SIZE]; // output buffer
2629  uint n;
2630  this->z.next_in = p;
2631  this->z.avail_in = (uInt)len;
2632  do {
2633  this->z.next_out = buf;
2634  this->z.avail_out = sizeof(buf);
2635 
2643  int r = deflate(&this->z, mode);
2644 
2645  /* bytes were emitted? */
2646  if ((n = sizeof(buf) - this->z.avail_out) != 0) {
2647  this->chain->Write(buf, n);
2648  }
2649  if (r == Z_STREAM_END) break;
2650 
2651  if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "zlib returned error code");
2652  } while (this->z.avail_in || !this->z.avail_out);
2653  }
2654 
2655  void Write(byte *buf, size_t size) override
2656  {
2657  this->WriteLoop(buf, size, 0);
2658  }
2659 
2660  void Finish() override
2661  {
2662  this->WriteLoop(nullptr, 0, Z_FINISH);
2663  this->chain->Finish();
2664  }
2665 };
2666 
2667 #endif /* WITH_ZLIB */
2668 
2669 /********************************************
2670  ********** START OF LZMA CODE **************
2671  ********************************************/
2672 
2673 #if defined(WITH_LIBLZMA)
2674 #include <lzma.h>
2675 
2682 static const lzma_stream _lzma_init = LZMA_STREAM_INIT;
2683 
2686  lzma_stream lzma;
2688 
2694  {
2695  /* Allow saves up to 256 MB uncompressed */
2696  if (lzma_auto_decoder(&this->lzma, 1 << 28, 0) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2697  }
2698 
2701  {
2702  lzma_end(&this->lzma);
2703  }
2704 
2705  size_t Read(byte *buf, size_t size) override
2706  {
2707  this->lzma.next_out = buf;
2708  this->lzma.avail_out = size;
2709 
2710  do {
2711  /* read more bytes from the file? */
2712  if (this->lzma.avail_in == 0) {
2713  this->lzma.next_in = this->fread_buf;
2714  this->lzma.avail_in = this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2715  }
2716 
2717  /* inflate the data */
2718  lzma_ret r = lzma_code(&this->lzma, LZMA_RUN);
2719  if (r == LZMA_STREAM_END) break;
2720  if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2721  } while (this->lzma.avail_out != 0);
2722 
2723  return size - this->lzma.avail_out;
2724  }
2725 };
2726 
2729  lzma_stream lzma;
2730 
2737  {
2738  if (lzma_easy_encoder(&this->lzma, compression_level, LZMA_CHECK_CRC32) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2739  }
2740 
2743  {
2744  lzma_end(&this->lzma);
2745  }
2746 
2753  void WriteLoop(byte *p, size_t len, lzma_action action)
2754  {
2755  byte buf[MEMORY_CHUNK_SIZE]; // output buffer
2756  size_t n;
2757  this->lzma.next_in = p;
2758  this->lzma.avail_in = len;
2759  do {
2760  this->lzma.next_out = buf;
2761  this->lzma.avail_out = sizeof(buf);
2762 
2763  lzma_ret r = lzma_code(&this->lzma, action);
2764 
2765  /* bytes were emitted? */
2766  if ((n = sizeof(buf) - this->lzma.avail_out) != 0) {
2767  this->chain->Write(buf, n);
2768  }
2769  if (r == LZMA_STREAM_END) break;
2770  if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2771  } while (this->lzma.avail_in || !this->lzma.avail_out);
2772  }
2773 
2774  void Write(byte *buf, size_t size) override
2775  {
2776  this->WriteLoop(buf, size, LZMA_RUN);
2777  }
2778 
2779  void Finish() override
2780  {
2781  this->WriteLoop(nullptr, 0, LZMA_FINISH);
2782  this->chain->Finish();
2783  }
2784 };
2785 
2786 #endif /* WITH_LIBLZMA */
2787 
2788 /*******************************************
2789  ************* END OF CODE *****************
2790  *******************************************/
2791 
2794  const char *name;
2795  uint32 tag;
2797  LoadFilter *(*init_load)(LoadFilter *chain);
2798  SaveFilter *(*init_write)(SaveFilter *chain, byte compression);
2801  byte default_compression;
2803 };
2807 #if defined(WITH_LZO)
2808  /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2809  {"lzo", TO_BE32X('OTTD'), CreateLoadFilter<LZOLoadFilter>, CreateSaveFilter<LZOSaveFilter>, 0, 0, 0},
2810 #else
2811  {"lzo", TO_BE32X('OTTD'), nullptr, nullptr, 0, 0, 0},
2812 #endif
2813  /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2814  {"none", TO_BE32X('OTTN'), CreateLoadFilter<NoCompLoadFilter>, CreateSaveFilter<NoCompSaveFilter>, 0, 0, 0},
2815 #if defined(WITH_ZLIB)
2816  /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2817  * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2818  * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2819  {"zlib", TO_BE32X('OTTZ'), CreateLoadFilter<ZlibLoadFilter>, CreateSaveFilter<ZlibSaveFilter>, 0, 6, 9},
2820 #else
2821  {"zlib", TO_BE32X('OTTZ'), nullptr, nullptr, 0, 0, 0},
2822 #endif
2823 #if defined(WITH_LIBLZMA)
2824  /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2825  * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2826  * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2827  * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2828  * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2829  {"lzma", TO_BE32X('OTTX'), CreateLoadFilter<LZMALoadFilter>, CreateSaveFilter<LZMASaveFilter>, 0, 2, 9},
2830 #else
2831  {"lzma", TO_BE32X('OTTX'), nullptr, nullptr, 0, 0, 0},
2832 #endif
2833 };
2834 
2842 static const SaveLoadFormat *GetSavegameFormat(const std::string &full_name, byte *compression_level)
2843 {
2844  const SaveLoadFormat *def = lastof(_saveload_formats);
2845 
2846  /* find default savegame format, the highest one with which files can be written */
2847  while (!def->init_write) def--;
2848 
2849  if (!full_name.empty()) {
2850  /* Get the ":..." of the compression level out of the way */
2851  size_t separator = full_name.find(':');
2852  bool has_comp_level = separator != std::string::npos;
2853  const std::string name(full_name, 0, has_comp_level ? separator : full_name.size());
2854 
2855  for (const SaveLoadFormat *slf = &_saveload_formats[0]; slf != endof(_saveload_formats); slf++) {
2856  if (slf->init_write != nullptr && name.compare(slf->name) == 0) {
2857  *compression_level = slf->default_compression;
2858  if (has_comp_level) {
2859  const std::string complevel(full_name, separator + 1);
2860 
2861  /* Get the level and determine whether all went fine. */
2862  size_t processed;
2863  long level = std::stol(complevel, &processed, 10);
2864  if (processed == 0 || level != Clamp(level, slf->min_compression, slf->max_compression)) {
2865  SetDParamStr(0, complevel);
2866  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL, WL_CRITICAL);
2867  } else {
2868  *compression_level = level;
2869  }
2870  }
2871  return slf;
2872  }
2873  }
2874 
2875  SetDParamStr(0, name);
2876  SetDParamStr(1, def->name);
2877  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM, WL_CRITICAL);
2878  }
2879  *compression_level = def->default_compression;
2880  return def;
2881 }
2882 
2883 /* actual loader/saver function */
2884 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
2885 extern bool AfterLoadGame();
2886 extern bool LoadOldSaveGame(const std::string &file);
2887 
2891 static void ResetSaveloadData()
2892 {
2893  ResetTempEngineData();
2894  ResetLabelMaps();
2895  ResetOldWaypoints();
2896 }
2897 
2901 static inline void ClearSaveLoadState()
2902 {
2903  delete _sl.dumper;
2904  _sl.dumper = nullptr;
2905 
2906  delete _sl.sf;
2907  _sl.sf = nullptr;
2908 
2909  delete _sl.reader;
2910  _sl.reader = nullptr;
2911 
2912  delete _sl.lf;
2913  _sl.lf = nullptr;
2914 }
2915 
2921 static void SaveFileStart()
2922 {
2924  _game_speed = 100;
2925  SetMouseCursorBusy(true);
2926 
2928  _sl.saveinprogress = true;
2929 }
2930 
2932 static void SaveFileDone()
2933 {
2934  if (_game_mode != GM_MENU) _game_speed = _sl.game_speed;
2935  SetMouseCursorBusy(false);
2936 
2938  _sl.saveinprogress = false;
2939 
2940 #ifdef __EMSCRIPTEN__
2941  EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
2942 #endif
2943 }
2944 
2947 {
2948  _sl.error_str = str;
2949 }
2950 
2953 {
2954  SetDParam(0, _sl.error_str);
2956 
2957  static char err_str[512];
2958  GetString(err_str, _sl.action == SLA_SAVE ? STR_ERROR_GAME_SAVE_FAILED : STR_ERROR_GAME_LOAD_FAILED, lastof(err_str));
2959  return err_str;
2960 }
2961 
2963 static void SaveFileError()
2964 {
2966  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
2967  SaveFileDone();
2968 }
2969 
2974 static SaveOrLoadResult SaveFileToDisk(bool threaded)
2975 {
2976  try {
2977  byte compression;
2978  const SaveLoadFormat *fmt = GetSavegameFormat(_savegame_format, &compression);
2979 
2980  /* We have written our stuff to memory, now write it to file! */
2981  uint32 hdr[2] = { fmt->tag, TO_BE32(SAVEGAME_VERSION << 16) };
2982  _sl.sf->Write((byte*)hdr, sizeof(hdr));
2983 
2984  _sl.sf = fmt->init_write(_sl.sf, compression);
2985  _sl.dumper->Flush(_sl.sf);
2986 
2988 
2989  if (threaded) SetAsyncSaveFinish(SaveFileDone);
2990 
2991  return SL_OK;
2992  } catch (...) {
2994 
2996 
2997  /* We don't want to shout when saving is just
2998  * cancelled due to a client disconnecting. */
2999  if (_sl.error_str != STR_NETWORK_ERROR_LOSTCONNECTION) {
3000  /* Skip the "colour" character */
3001  Debug(sl, 0, "{}", GetSaveLoadErrorString() + 3);
3002  asfp = SaveFileError;
3003  }
3004 
3005  if (threaded) {
3006  SetAsyncSaveFinish(asfp);
3007  } else {
3008  asfp();
3009  }
3010  return SL_ERROR;
3011  }
3012 }
3013 
3014 void WaitTillSaved()
3015 {
3016  if (!_save_thread.joinable()) return;
3017 
3018  _save_thread.join();
3019 
3020  /* Make sure every other state is handled properly as well. */
3022 }
3023 
3032 static SaveOrLoadResult DoSave(SaveFilter *writer, bool threaded)
3033 {
3034  assert(!_sl.saveinprogress);
3035 
3036  _sl.dumper = new MemoryDumper();
3037  _sl.sf = writer;
3038 
3040 
3041  SaveViewportBeforeSaveGame();
3042  SlSaveChunks();
3043 
3044  SaveFileStart();
3045 
3046  if (!threaded || !StartNewThread(&_save_thread, "ottd:savegame", &SaveFileToDisk, true)) {
3047  if (threaded) Debug(sl, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
3048 
3049  SaveOrLoadResult result = SaveFileToDisk(false);
3050  SaveFileDone();
3051 
3052  return result;
3053  }
3054 
3055  return SL_OK;
3056 }
3057 
3065 {
3066  try {
3067  _sl.action = SLA_SAVE;
3068  return DoSave(writer, threaded);
3069  } catch (...) {
3071  return SL_ERROR;
3072  }
3073 }
3074 
3081 static SaveOrLoadResult DoLoad(LoadFilter *reader, bool load_check)
3082 {
3083  _sl.lf = reader;
3084 
3085  if (load_check) {
3086  /* Clear previous check data */
3088  /* Mark SL_LOAD_CHECK as supported for this savegame. */
3089  _load_check_data.checkable = true;
3090  }
3091 
3092  uint32 hdr[2];
3093  if (_sl.lf->Read((byte*)hdr, sizeof(hdr)) != sizeof(hdr)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3094 
3095  /* see if we have any loader for this type. */
3096  const SaveLoadFormat *fmt = _saveload_formats;
3097  for (;;) {
3098  /* No loader found, treat as version 0 and use LZO format */
3099  if (fmt == endof(_saveload_formats)) {
3100  Debug(sl, 0, "Unknown savegame type, trying to load it as the buggy format");
3101  _sl.lf->Reset();
3103  _sl_minor_version = 0;
3104 
3105  /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
3106  fmt = _saveload_formats;
3107  for (;;) {
3108  if (fmt == endof(_saveload_formats)) {
3109  /* Who removed LZO support? */
3110  NOT_REACHED();
3111  }
3112  if (fmt->tag == TO_BE32X('OTTD')) break;
3113  fmt++;
3114  }
3115  break;
3116  }
3117 
3118  if (fmt->tag == hdr[0]) {
3119  /* check version number */
3120  _sl_version = (SaveLoadVersion)(TO_BE32(hdr[1]) >> 16);
3121  /* Minor is not used anymore from version 18.0, but it is still needed
3122  * in versions before that (4 cases) which can't be removed easy.
3123  * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
3124  _sl_minor_version = (TO_BE32(hdr[1]) >> 8) & 0xFF;
3125 
3126  Debug(sl, 1, "Loading savegame version {}", _sl_version);
3127 
3128  /* Is the version higher than the current? */
3129  if (_sl_version > SAVEGAME_VERSION) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME);
3130  if (_sl_version >= SLV_START_PATCHPACKS && _sl_version <= SLV_END_PATCHPACKS) SlError(STR_GAME_SAVELOAD_ERROR_PATCHPACK);
3131  break;
3132  }
3133 
3134  fmt++;
3135  }
3136 
3137  /* loader for this savegame type is not implemented? */
3138  if (fmt->init_load == nullptr) {
3139  char err_str[64];
3140  seprintf(err_str, lastof(err_str), "Loader for '%s' is not available.", fmt->name);
3141  SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, err_str);
3142  }
3143 
3144  _sl.lf = fmt->init_load(_sl.lf);
3145  _sl.reader = new ReadBuffer(_sl.lf);
3146  _next_offs = 0;
3147 
3148  if (!load_check) {
3150 
3151  /* Old maps were hardcoded to 256x256 and thus did not contain
3152  * any mapsize information. Pre-initialize to 256x256 to not to
3153  * confuse old games */
3154  InitializeGame(256, 256, true, true);
3155 
3156  GamelogReset();
3157 
3159  /*
3160  * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
3161  * shared savegame version 4. Anything before that 'obviously'
3162  * does not have any NewGRFs. Between the introduction and
3163  * savegame version 41 (just before 0.5) the NewGRF settings
3164  * were not stored in the savegame and they were loaded by
3165  * using the settings from the main menu.
3166  * So, to recap:
3167  * - savegame version < 4: do not load any NewGRFs.
3168  * - savegame version >= 41: load NewGRFs from savegame, which is
3169  * already done at this stage by
3170  * overwriting the main menu settings.
3171  * - other savegame versions: use main menu settings.
3172  *
3173  * This means that users *can* crash savegame version 4..40
3174  * savegames if they set incompatible NewGRFs in the main menu,
3175  * but can't crash anymore for savegame version < 4 savegames.
3176  *
3177  * Note: this is done here because AfterLoadGame is also called
3178  * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
3179  */
3181  }
3182  }
3183 
3184  if (load_check) {
3185  /* Load chunks into _load_check_data.
3186  * No pools are loaded. References are not possible, and thus do not need resolving. */
3188  } else {
3189  /* Load chunks and resolve references */
3190  SlLoadChunks();
3191  SlFixPointers();
3192  }
3193 
3195 
3197 
3198  if (load_check) {
3199  /* The only part from AfterLoadGame() we need */
3201  } else {
3203 
3204  /* After loading fix up savegame for any internal changes that
3205  * might have occurred since then. If it fails, load back the old game. */
3206  if (!AfterLoadGame()) {
3208  return SL_REINIT;
3209  }
3210 
3212  }
3213 
3214  return SL_OK;
3215 }
3216 
3223 {
3224  try {
3225  _sl.action = SLA_LOAD;
3226  return DoLoad(reader, false);
3227  } catch (...) {
3229  return SL_REINIT;
3230  }
3231 }
3232 
3242 SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
3243 {
3244  /* An instance of saving is already active, so don't go saving again */
3245  if (_sl.saveinprogress && fop == SLO_SAVE && dft == DFT_GAME_FILE && threaded) {
3246  /* if not an autosave, but a user action, show error message */
3247  if (!_do_autosave) ShowErrorMessage(STR_ERROR_SAVE_STILL_IN_PROGRESS, INVALID_STRING_ID, WL_ERROR);
3248  return SL_OK;
3249  }
3250  WaitTillSaved();
3251 
3252  try {
3253  /* Load a TTDLX or TTDPatch game */
3254  if (fop == SLO_LOAD && dft == DFT_OLD_GAME_FILE) {
3256 
3257  InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
3258 
3259  /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
3260  * and if so a new NewGRF list will be made in LoadOldSaveGame.
3261  * Note: this is done here because AfterLoadGame is also called
3262  * for OTTD savegames which have their own NewGRF logic. */
3264  GamelogReset();
3265  if (!LoadOldSaveGame(filename)) return SL_REINIT;
3267  _sl_minor_version = 0;
3269  if (!AfterLoadGame()) {
3271  return SL_REINIT;
3272  }
3274  return SL_OK;
3275  }
3276 
3277  assert(dft == DFT_GAME_FILE);
3278  switch (fop) {
3279  case SLO_CHECK:
3281  break;
3282 
3283  case SLO_LOAD:
3284  _sl.action = SLA_LOAD;
3285  break;
3286 
3287  case SLO_SAVE:
3288  _sl.action = SLA_SAVE;
3289  break;
3290 
3291  default: NOT_REACHED();
3292  }
3293 
3294  FILE *fh = (fop == SLO_SAVE) ? FioFOpenFile(filename, "wb", sb) : FioFOpenFile(filename, "rb", sb);
3295 
3296  /* Make it a little easier to load savegames from the console */
3297  if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SAVE_DIR);
3298  if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", BASE_DIR);
3299  if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SCENARIO_DIR);
3300 
3301  if (fh == nullptr) {
3302  SlError(fop == SLO_SAVE ? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE : STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3303  }
3304 
3305  if (fop == SLO_SAVE) { // SAVE game
3306  Debug(desync, 1, "save: {:08x}; {:02x}; {}", _date, _date_fract, filename);
3307  if (_network_server || !_settings_client.gui.threaded_saves) threaded = false;
3308 
3309  return DoSave(new FileWriter(fh), threaded);
3310  }
3311 
3312  /* LOAD game */
3313  assert(fop == SLO_LOAD || fop == SLO_CHECK);
3314  Debug(desync, 1, "load: {}", filename);
3315  return DoLoad(new FileReader(fh), fop == SLO_CHECK);
3316  } catch (...) {
3317  /* This code may be executed both for old and new save games. */
3319 
3320  /* Skip the "colour" character */
3321  if (fop != SLO_CHECK) Debug(sl, 0, "{}", GetSaveLoadErrorString());
3322 
3323  /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3324  return (fop == SLO_LOAD) ? SL_REINIT : SL_ERROR;
3325  }
3326 }
3327 
3334 {
3335  char buf[MAX_PATH];
3336 
3338  GenerateDefaultSaveName(buf, lastof(buf));
3339  strecat(buf, counter.Extension().c_str(), lastof(buf));
3340  } else {
3341  strecpy(buf, counter.Filename().c_str(), lastof(buf));
3342  }
3343 
3344  Debug(sl, 2, "Autosaving to '{}'", buf);
3346  ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
3347  }
3348 }
3349 
3350 
3353 {
3355 }
3356 
3362 void GenerateDefaultSaveName(char *buf, const char *last)
3363 {
3364  /* Check if we have a name for this map, which is the name of the first
3365  * available company. When there's no company available we'll use
3366  * 'Spectator' as "company" name. */
3367  CompanyID cid = _local_company;
3368  if (!Company::IsValidID(cid)) {
3369  for (const Company *c : Company::Iterate()) {
3370  cid = c->index;
3371  break;
3372  }
3373  }
3374 
3375  SetDParam(0, cid);
3376 
3377  /* Insert current date */
3379  case 0: SetDParam(1, STR_JUST_DATE_LONG); break;
3380  case 1: SetDParam(1, STR_JUST_DATE_TINY); break;
3381  case 2: SetDParam(1, STR_JUST_DATE_ISO); break;
3382  default: NOT_REACHED();
3383  }
3384  SetDParam(2, _date);
3385 
3386  /* Get the correct string (special string for when there's not company) */
3387  GetString(buf, !Company::IsValidID(cid) ? STR_SAVEGAME_NAME_SPECTATOR : STR_SAVEGAME_NAME_DEFAULT, last);
3388  SanitizeFilename(buf);
3389 }
3390 
3396 {
3398 }
3399 
3407 {
3408  if (aft == FT_INVALID || aft == FT_NONE) {
3409  this->file_op = SLO_INVALID;
3410  this->detail_ftype = DFT_INVALID;
3411  this->abstract_ftype = FT_INVALID;
3412  return;
3413  }
3414 
3415  this->file_op = fop;
3416  this->detail_ftype = dft;
3417  this->abstract_ftype = aft;
3418 }
3419 
3424 void FileToSaveLoad::SetName(const char *name)
3425 {
3426  this->name = name;
3427 }
3428 
3433 void FileToSaveLoad::SetTitle(const char *title)
3434 {
3435  strecpy(this->title, title, lastof(this->title));
3436 }
3437 
3439 {
3440  assert(this->load_description.has_value());
3441  return *this->load_description;
3442 }
FileToSaveLoad::title
char title[255]
Internal name of the game.
Definition: saveload.h:363
SL_NULL
@ SL_NULL
Save null-bytes and load to nowhere.
Definition: saveload.h:652
ZlibLoadFilter::fread_buf
byte fread_buf[MEMORY_CHUNK_SIZE]
Buffer for reading from the file.
Definition: saveload.cpp:2560
SlLoadChunks
static void SlLoadChunks()
Load all chunks.
Definition: saveload.cpp:2298
SlCalcTableHeader
static size_t SlCalcTableHeader(const SaveLoadTable &slt)
Calculate the size of the table header.
Definition: saveload.cpp:1567
ResetSaveloadData
static void ResetSaveloadData()
Clear temporary data that is passed between various saveload phases.
Definition: saveload.cpp:2891
IsVariableSizeRight
static bool IsVariableSizeRight(const SaveLoad &sld)
Check whether the variable size of the variable in the saveload configuration matches with the actual...
Definition: saveload.cpp:1659
SlStorageHelper::SlSaveLoad
static void SlSaveLoad(void *storage, VarType conv, SaveLoadType cmd=SL_VAR)
Internal templated helper to save/load a list-like type.
Definition: saveload.cpp:1398
SetMouseCursorBusy
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
Definition: gfx.cpp:1893
SaveLoad::version_to
SaveLoadVersion version_to
Save/load the variable before this savegame version.
Definition: saveload.h:664
SaveLoadFormat::init_write
SaveFilter *(* init_write)(SaveFilter *chain, byte compression)
Constructor for the save filter.
Definition: saveload.cpp:2800
FileWriter::FileWriter
FileWriter(FILE *file)
Create the file writer, so it writes to a specific file.
Definition: saveload.cpp:2389
SlIsObjectValidInSavegame
static bool SlIsObjectValidInSavegame(const SaveLoad &sld)
Are we going to save this object or not?
Definition: saveload.cpp:1557
LZMASaveFilter::lzma
lzma_stream lzma
Stream state that we are writing to.
Definition: saveload.cpp:2729
SLV_69
@ SLV_69
69 10319
Definition: saveload.h:129
InvalidateWindowData
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:3241
LZO_BUFFER_SIZE
static const uint LZO_BUFFER_SIZE
Buffer size for the LZO compressor.
Definition: saveload.cpp:2425
REF_ORDER
@ REF_ORDER
Load/save a reference to an order.
Definition: saveload.h:540
SaveLoadType
SaveLoadType
Type of data saved.
Definition: saveload.h:637
SlDeque
static void SlDeque(void *deque, VarType conv)
Save/load a std::deque.
Definition: saveload.cpp:1498
SLV_169
@ SLV_169
169 23816
Definition: saveload.h:249
SlLoadChunk
static void SlLoadChunk(const ChunkHandler &ch)
Load a chunk of data (eg vehicles, stations, etc.)
Definition: saveload.cpp:2141
LoadCheckData::checkable
bool checkable
True if the savegame could be checked by SL_LOAD_CHECK. (Old savegames are not checkable....
Definition: fios.h:32
SetSaveLoadError
void SetSaveLoadError(StringID str)
Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friend...
Definition: saveload.cpp:2946
ZlibLoadFilter::~ZlibLoadFilter
~ZlibLoadFilter()
Clean everything up.
Definition: saveload.cpp:2573
Pool::PoolItem<&_orderlist_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
SAVE_DIR
@ SAVE_DIR
Base directory for all savegames.
Definition: fileio_type.h:110
SaveLoadFormat::min_compression
byte min_compression
the minimum compression level of this format
Definition: saveload.cpp:2802
SlArray
static void SlArray(void *array, size_t length, VarType conv)
Save/Load the length of the array followed by the array of SL_VAR elements.
Definition: saveload.cpp:1183
SGT_OTTD
@ SGT_OTTD
OTTD savegame.
Definition: saveload.h:376
SVS_ALLOW_NEWLINE
@ SVS_ALLOW_NEWLINE
Allow newlines.
Definition: string_type.h:52
LinkGraph
A connected component of a link graph.
Definition: linkgraph.h:39
_save_thread
static std::thread _save_thread
The thread we're using to compress and write a savegame.
Definition: saveload.cpp:393
SLE_VAR_STR
@ SLE_VAR_STR
string pointer
Definition: saveload.h:594
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
LZMALoadFilter::LZMALoadFilter
LZMALoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2693
GetVarFileType
static VarType GetVarFileType(VarType type)
Get the FileType of a setting.
Definition: saveload.h:1079
LZMASaveFilter::LZMASaveFilter
LZMASaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2736
NoCompLoadFilter
Filter without any compression.
Definition: saveload.cpp:2516
_sl_minor_version
byte _sl_minor_version
the minor savegame version, DO NOT USE!
Definition: saveload.cpp:67
GLAT_LOAD
@ GLAT_LOAD
Game loaded.
Definition: gamelog.h:18
LZMALoadFilter::fread_buf
byte fread_buf[MEMORY_CHUNK_SIZE]
Buffer for reading from the file.
Definition: saveload.cpp:2687
SLA_SAVE
@ SLA_SAVE
saving
Definition: saveload.cpp:74
RemapOldStringID
StringID RemapOldStringID(StringID s)
Remap a string ID from the old format to the new format.
Definition: strings_sl.cpp:29
CSleep
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:23
SL_MIN_VERSION
@ SL_MIN_VERSION
First savegame version.
Definition: saveload.h:35
SaveLoadFormat::init_load
LoadFilter *(* init_load)(LoadFilter *chain)
Constructor for the load filter.
Definition: saveload.cpp:2799
REF_TOWN
@ REF_TOWN
Load/save a reference to a town.
Definition: saveload.h:543
DoExitSave
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:3352
ClearGRFConfigList
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
Definition: newgrf_config.cpp:400
NoCompLoadFilter::NoCompLoadFilter
NoCompLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2523
GUISettings::date_format_in_default_names
uint8 date_format_in_default_names
should the default savegame/screenshot name use long dates (31th Dec 2008), short dates (31-12-2008) ...
Definition: settings_type.h:140
NoCompSaveFilter::NoCompSaveFilter
NoCompSaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2538
SL_STR
@ SL_STR
Save/load a string.
Definition: saveload.h:642
REF_ROADSTOPS
@ REF_ROADSTOPS
Load/save a reference to a bus/truck stop.
Definition: saveload.h:545
FileToSaveLoad::SetTitle
void SetTitle(const char *title)
Set the title of the file.
Definition: saveload.cpp:3433
SLE_FILE_END
@ SLE_FILE_END
Used to mark end-of-header in tables.
Definition: saveload.h:565
FileReader::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2364
Station
Station data structure.
Definition: station_base.h:454
SlSkipArray
void SlSkipArray()
Skip an array or sparse array.
Definition: saveload.cpp:713
LinkGraphJob
Class for calculation jobs to be run on link graphs.
Definition: linkgraphjob.h:30
SaveOrLoad
SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
Definition: saveload.cpp:3242
_date_fract
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
_network_server
bool _network_server
network-server is active
Definition: network.cpp:59
SaveLoadOperation
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:47
SlCopy
void SlCopy(void *object, size_t length, VarType conv)
Copy a list of SL_VARs to/from a savegame.
Definition: saveload.cpp:1153
FileToSaveLoad::name
std::string name
Name of the file.
Definition: saveload.h:362
str_fix_scc_encoded
void str_fix_scc_encoded(char *str, const char *last)
Scan the string for old values of SCC_ENCODED and fix it to it's new, static value.
Definition: string.cpp:187
FileReader::begin
long begin
The begin of the file.
Definition: saveload.cpp:2344
SaveLoad::size
size_t size
The sizeof size.
Definition: saveload.h:665
_load_check_data
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition: fios_gui.cpp:39
LZOLoadFilter::LZOLoadFilter
LZOLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2433
AfterLoadGame
bool AfterLoadGame()
Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill th...
Definition: afterload.cpp:545
SLF_ALLOW_NEWLINE
@ SLF_ALLOW_NEWLINE
Allow new lines in the strings.
Definition: saveload.h:631
ZlibLoadFilter::ZlibLoadFilter
ZlibLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2566
SlSaveChunks
static void SlSaveChunks()
Save all chunks.
Definition: saveload.cpp:2275
SLA_LOAD_CHECK
@ SLA_LOAD_CHECK
partial loading into _load_check_data
Definition: saveload.cpp:77
SLO_CHECK
@ SLO_CHECK
Load file for checking and/or preview.
Definition: fileio_type.h:48
SLE_STR
#define SLE_STR(base, variable, type, length)
Storage of a string in every savegame version.
Definition: saveload.h:803
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
MemoryDumper::MemoryDumper
MemoryDumper()
Initialise our variables.
Definition: saveload.cpp:137
_do_autosave
bool _do_autosave
are we doing an autosave at the moment?
Definition: saveload.cpp:69
LZOSaveFilter::LZOSaveFilter
LZOSaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2481
MemoryDumper::GetSize
size_t GetSize() const
Get the size of the memory dump made so far.
Definition: saveload.cpp:187
DFT_GAME_FILE
@ DFT_GAME_FILE
Save game or scenario file.
Definition: fileio_type.h:31
FileToSaveLoad
Deals with the type of the savegame, independent of extension.
Definition: saveload.h:358
LoadCheckData::grfconfig
GRFConfig * grfconfig
NewGrf configuration from save.
Definition: fios.h:43
FileToSaveLoad::SetName
void SetName(const char *name)
Set the name of the file.
Definition: saveload.cpp:3424
SaveLoadFormat::max_compression
byte max_compression
the maximum compression level of this format
Definition: saveload.cpp:2804
SLE_VAR_NULL
@ SLE_VAR_NULL
useful to write zeros in savegame.
Definition: saveload.h:592
LZOLoadFilter::Read
size_t Read(byte *buf, size_t ssize) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2438
GetSavegameFileType
static uint8 GetSavegameFileType(const SaveLoad &sld)
Return the type as saved/loaded inside the savegame.
Definition: saveload.cpp:586
SaveLoadHandler::GetLoadDescription
SaveLoadTable GetLoadDescription() const
Get the description for how to load the chunk.
Definition: saveload.cpp:3438
ChunkHandler::type
ChunkType type
Type of the chunk.
Definition: saveload.h:413
SaveLoad::length
uint16 length
(Conditional) length of the variable (eg. arrays) (max array size is 65536 elements).
Definition: saveload.h:662
ReadBuffer
A buffer for reading (and buffering) savegame data.
Definition: saveload.cpp:90
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:218
AUTOSAVE_DIR
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Definition: fileio_type.h:111
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:53
GetDetailedFileType
DetailedFileType GetDetailedFileType(FiosType fios_type)
Extract the detailed file type from a FiosType.
Definition: fileio_type.h:100
SlNullPointers
static void SlNullPointers()
Null all pointers (convert index -> nullptr)
Definition: saveload.cpp:309
SpecializedStation< Station, false >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index is a valid index for station of this type.
Definition: base_station_base.h:209
SLA_LOAD
@ SLA_LOAD
loading
Definition: saveload.cpp:73
SaveLoadParams::reader
ReadBuffer * reader
Savegame reading buffer.
Definition: saveload.cpp:207
ZlibLoadFilter
Filter using Zlib compression.
Definition: saveload.cpp:2556
LoadWithFilter
SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
Load the game using a (reader) filter.
Definition: saveload.cpp:3222
ChunkHandler
Handlers and description of chunk.
Definition: saveload.h:411
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:224
SaveLoad::conv
VarType conv
Type of the variable to be saved; this field combines both FileVarType and MemVarType.
Definition: saveload.h:661
LZMASaveFilter::WriteLoop
void WriteLoop(byte *p, size_t len, lzma_action action)
Helper loop for writing the data.
Definition: saveload.cpp:2753
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
SlCalcConvFileLen
static byte SlCalcConvFileLen(VarType conv)
Return the size in bytes of a certain type of normal/atomic variable as it appears in a saved game.
Definition: saveload.cpp:645
SaveLoadFormat::default_compression
byte default_compression
the default compression level of this format
Definition: saveload.cpp:2803
SaveLoadAction
SaveLoadAction
What are we currently doing?
Definition: saveload.cpp:72
LoadFilter::Reset
virtual void Reset()
Reset this filter to read from the beginning of the file.
Definition: saveload_filter.h:43
SaveLoadParams::sf
SaveFilter * sf
Filter to write the savegame to.
Definition: saveload.cpp:205
SaveLoadHandler
Handler for saving/loading an object to/from disk.
Definition: saveload.h:460
SlSkipHandler::Load
void Load(void *object) const override
Load the object from disk.
Definition: saveload.cpp:1863
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:196
SlCalcStdStringLen
static size_t SlCalcStdStringLen(const void *ptr)
Calculate the gross length of the string that it will occupy in the savegame.
Definition: saveload.cpp:957
NL_NONE
@ NL_NONE
not working in NeedLength mode
Definition: saveload.cpp:81
AsyncSaveFinishProc
void(* AsyncSaveFinishProc)()
Callback for when the savegame loading is finished.
Definition: saveload.cpp:391
SlSetLength
void SlSetLength(size_t length)
Sets the length of either a RIFF object or the number of items in an array.
Definition: saveload.cpp:725
NoCompLoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2527
ZlibSaveFilter::z
z_stream z
Stream state we are writing to.
Definition: saveload.cpp:2601
SlReadSimpleGamma
static uint SlReadSimpleGamma()
Read in the header descriptor of an object or an array.
Definition: saveload.cpp:486
SLE_FILE_TYPE_MASK
@ SLE_FILE_TYPE_MASK
Mask to get the file-type (and not any flags).
Definition: saveload.h:579
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:377
saveload_filter.h
ReadBuffer::reader
LoadFilter * reader
The filter used to actually read.
Definition: saveload.cpp:94
MemoryDumper::buf
byte * buf
Buffer we're going to write to.
Definition: saveload.cpp:133
SlGlobList
void SlGlobList(const SaveLoadTable &slt)
Save or Load (a list of) global variables.
Definition: saveload.cpp:2085
NoCompSaveFilter
Filter without any compression.
Definition: saveload.cpp:2532
REF_STATION
@ REF_STATION
Load/save a reference to a station.
Definition: saveload.h:542
LZMALoadFilter
Filter without any compression.
Definition: saveload.cpp:2685
SLE_VAR_STRB
@ SLE_VAR_STRB
string (with pre-allocated buffer)
Definition: saveload.h:593
SlCalcConvMemLen
static uint SlCalcConvMemLen(VarType conv)
Return the size in bytes of a certain type of normal/atomic variable as it appears in memory.
Definition: saveload.cpp:622
AbstractFileType
AbstractFileType
The different abstract types of files that the system knows about.
Definition: fileio_type.h:16
LoadFilter::Read
virtual size_t Read(byte *buf, size_t len)=0
Read a given number of bytes from the savegame.
ReferenceToInt
static size_t ReferenceToInt(const void *obj, SLRefType rt)
Pointers cannot be saved to a savegame, so this functions gets the index of the item,...
Definition: saveload.cpp:1229
SaveLoadFormat
The format for a reader/writer type of a savegame.
Definition: saveload.cpp:2793
FileToSaveLoad::abstract_ftype
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition: saveload.h:361
ReadBuffer::buf
byte buf[MEMORY_CHUNK_SIZE]
Buffer we're going to read from.
Definition: saveload.cpp:91
SaveLoadParams::block_mode
byte block_mode
???
Definition: saveload.cpp:197
FileWriter::file
FILE * file
The file to write to.
Definition: saveload.cpp:2383
SVS_ALLOW_CONTROL_CODE
@ SVS_ALLOW_CONTROL_CODE
Allow the special control codes.
Definition: string_type.h:53
BASE_DIR
@ BASE_DIR
Base directory for all subdirectories.
Definition: fileio_type.h:109
SLV_5
@ SLV_5
5.0 1429 5.1 1440 5.2 1525 0.3.6
Definition: saveload.h:47
SL_SAVEBYTE
@ SL_SAVEBYTE
Save (but not load) a byte.
Definition: saveload.h:651
SaveFileDone
static void SaveFileDone()
Update the gui accordingly when saving is done and release locks on saveload.
Definition: saveload.cpp:2932
SLF_ALLOW_CONTROL
@ SLF_ALLOW_CONTROL
Allow control codes in the strings.
Definition: saveload.h:630
SlSkipHandler
Handler that is assigned when there is a struct read in the savegame which is not known to the code.
Definition: saveload.cpp:1857
MemoryDumper::WriteByte
void WriteByte(byte b)
Write a single byte into the dumper.
Definition: saveload.cpp:152
SLE_FILE_HAS_LENGTH_FIELD
@ SLE_FILE_HAS_LENGTH_FIELD
Bit stored in savegame to indicate field has a length field for each entry.
Definition: saveload.h:580
SLO_LOAD
@ SLO_LOAD
File is being loaded.
Definition: fileio_type.h:49
SaveFileError
static void SaveFileError()
Show a gui message when saving has failed.
Definition: saveload.cpp:2963
IsGoodGRFConfigList
GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
Check if all GRFs in the GRF config from a savegame can be loaded.
Definition: newgrf_config.cpp:513
_sl_version
SaveLoadVersion _sl_version
the major savegame version identifier
Definition: saveload.cpp:66
SlFixPointers
static void SlFixPointers()
Fix all pointers (convert index -> pointer)
Definition: saveload.cpp:2328
SavegameType
SavegameType
Types of save games.
Definition: saveload.h:372
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
SAVEGAME_VERSION
const SaveLoadVersion SAVEGAME_VERSION
Current savegame version of OpenTTD.
ZlibSaveFilter
Filter using Zlib compression.
Definition: saveload.cpp:2600
SLO_SAVE
@ SLO_SAVE
File is being saved.
Definition: fileio_type.h:50
SBI_SAVELOAD_FINISH
@ SBI_SAVELOAD_FINISH
finished saving
Definition: statusbar_gui.h:16
IntToReference
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...
Definition: saveload.cpp:1262
NeedLength
NeedLength
Definition: saveload.cpp:80
SlSaveLoadRef
void SlSaveLoadRef(void *ptr, VarType conv)
Handle conversion for references.
Definition: saveload.cpp:1338
CH_TYPE_MASK
@ CH_TYPE_MASK
All ChunkType values have to be within this mask.
Definition: saveload.h:406
span
A trimmed down version of what std::span will be in C++20.
Definition: span_type.hpp:60
NL_CALCLENGTH
@ NL_CALCLENGTH
need to calculate the length
Definition: saveload.cpp:83
SaveFilter::Finish
virtual void Finish()
Prepare everything to finish writing the savegame.
Definition: saveload_filter.h:88
ChunkHandler::Save
virtual void Save() const
Save the chunk.
Definition: saveload.h:423
CH_READONLY
@ CH_READONLY
Chunk is never saved.
Definition: saveload.h:407
SlCalcDequeLen
static size_t SlCalcDequeLen(const void *deque, VarType conv)
Return the size in bytes of a std::deque.
Definition: saveload.cpp:1477
SlWriteByte
void SlWriteByte(byte b)
Wrapper for writing a byte to the dumper.
Definition: saveload.cpp:435
ChunkHandler::id
uint32 id
Unique ID (4 letters).
Definition: saveload.h:412
SL_VAR
@ SL_VAR
Save/load a variable.
Definition: saveload.h:638
StrMakeValidInPlace
void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:273
_savegame_format
std::string _savegame_format
how to compress savegames
Definition: saveload.cpp:68
FioFOpenFile
FILE * FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:245
LoadCheckData::error_data
char * error_data
Data to pass to SetDParamStr when displaying error.
Definition: fios.h:34
LZMASaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2774
NL_WANTLENGTH
@ NL_WANTLENGTH
writing length and data
Definition: saveload.cpp:82
GetSaveLoadErrorString
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
Definition: saveload.cpp:2952
ZlibLoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2578
SlCopyInternal
static void SlCopyInternal(void *object, size_t length, VarType conv)
Internal function to save/Load a list of SL_VARs.
Definition: saveload.cpp:1104
SaveFilter::Write
virtual void Write(byte *buf, size_t len)=0
Write a given number of bytes into the savegame.
PersistentStorage
Class for pooled persistent storage of data.
Definition: newgrf_storage.h:221
_savegame_type
SavegameType _savegame_type
type of savegame we are loading
Definition: saveload.cpp:62
SlLoadCheckChunks
static void SlLoadCheckChunks()
Load all chunks for savegame checking.
Definition: saveload.cpp:2313
ZlibSaveFilter::ZlibSaveFilter
ZlibSaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2608
CopyFromOldName
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
Definition: strings_sl.cpp:60
SlVector
static void SlVector(void *vector, VarType conv)
Save/load a std::vector.
Definition: saveload.cpp:1540
FileReader::file
FILE * file
The file to read from.
Definition: saveload.cpp:2343
SL_REINIT
@ SL_REINIT
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
Definition: saveload.h:354
SaveLoad::cmd
SaveLoadType cmd
The action to take with the saved/loaded type, All types need different action.
Definition: saveload.h:660
SLV_END_PATCHPACKS
@ SLV_END_PATCHPACKS
286 Last known patchpack to use a version just above ours.
Definition: saveload.h:326
SLRefType
SLRefType
Type of reference (SLE_REF, SLE_CONDREF).
Definition: saveload.h:539
StartNewThread
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:46
SlSaveLoadConv
static void SlSaveLoadConv(void *ptr, VarType conv)
Handle all conversion and typechecking of variables here.
Definition: saveload.cpp:856
ZlibSaveFilter::WriteLoop
void WriteLoop(byte *p, size_t len, int mode)
Helper loop for writing the data.
Definition: saveload.cpp:2626
FileWriter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2402
GamelogStartAction
void GamelogStartAction(GamelogActionType at)
Stores information about new action, but doesn't allocate it Action is allocated only when there is a...
Definition: gamelog.cpp:69
GetSavegameFormat
static const SaveLoadFormat * GetSavegameFormat(const std::string &full_name, byte *compression_level)
Return the savegameformat of the game.
Definition: saveload.cpp:2842
SaveLoadParams::lf
LoadFilter * lf
Filter to read the savegame from.
Definition: saveload.cpp:208
NoCompSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2542
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
SaveFileToDisk
static SaveOrLoadResult SaveFileToDisk(bool threaded)
We have written the whole game into memory, _memory_savegame, now find and appropriate compressor and...
Definition: saveload.cpp:2974
SaveLoadFormat::name
const char * name
name of the compressor/decompressor (debug-only)
Definition: saveload.cpp:2796
SlCalcRefListLen
static size_t SlCalcRefListLen(const void *list, VarType conv)
Return the size in bytes of a list.
Definition: saveload.cpp:1450
GUISettings::keep_all_autosave
bool keep_all_autosave
name the autosave in a different way
Definition: settings_type.h:137
ChunkHandlers
static const std::vector< ChunkHandlerRef > & ChunkHandlers()
Definition: saveload.cpp:219
SL_ARR
@ SL_ARR
Save/load a fixed-size array of SL_VAR elements.
Definition: saveload.h:645
SLE_FILE_STRINGID
@ SLE_FILE_STRINGID
StringID offset into strings-array.
Definition: saveload.h:574
REF_STORAGE
@ REF_STORAGE
Load/save a reference to a persistent storage.
Definition: saveload.h:549
SCENARIO_DIR
@ SCENARIO_DIR
Base directory for all scenarios.
Definition: fileio_type.h:112
FT_INVALID
@ FT_INVALID
Invalid or unknown file type.
Definition: fileio_type.h:22
SaveLoadVersion
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition: saveload.h:34
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
SLA_PTRS
@ SLA_PTRS
fixing pointers
Definition: saveload.cpp:75
IsSavegameVersionBefore
static bool IsSavegameVersionBefore(SaveLoadVersion major, byte minor=0)
Checks whether the savegame is below major.
Definition: saveload.h:1029
MemoryDumper::Flush
void Flush(SaveFilter *writer)
Flush this dumper into a writer.
Definition: saveload.cpp:168
SaveFileStart
static void SaveFileStart()
Update the gui accordingly when starting saving and set locks on saveload.
Definition: saveload.cpp:2921
REF_ENGINE_RENEWS
@ REF_ENGINE_RENEWS
Load/save a reference to an engine renewal (autoreplace).
Definition: saveload.h:546
DFT_OLD_GAME_FILE
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
Definition: fileio_type.h:30
vseprintf
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:62
REF_VEHICLE
@ REF_VEHICLE
Load/save a reference to a vehicle.
Definition: saveload.h:541
SL_REF
@ SL_REF
Save/load a reference.
Definition: saveload.h:639
DoAutoOrNetsave
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
Definition: saveload.cpp:3333
REF_CARGO_PACKET
@ REF_CARGO_PACKET
Load/save a reference to a cargo packet.
Definition: saveload.h:547
SL_STRUCT
@ SL_STRUCT
Save/load a struct.
Definition: saveload.h:640
DoSave
static SaveOrLoadResult DoSave(SaveFilter *writer, bool threaded)
Actually perform the saving of the savegame.
Definition: saveload.cpp:3032
SBI_SAVELOAD_START
@ SBI_SAVELOAD_START
started saving
Definition: statusbar_gui.h:15
LZMALoadFilter::lzma
lzma_stream lzma
Stream state that we are reading from.
Definition: saveload.cpp:2686
ReadBuffer::bufp
byte * bufp
Location we're at reading the buffer.
Definition: saveload.cpp:92
SlAutolength
void SlAutolength(AutolengthProc *proc, void *arg)
Do something of which I have no idea what it is :P.
Definition: saveload.cpp:2095
EngineRenew
Struct to store engine replacements.
Definition: autoreplace_base.h:33
REF_VEHICLE_OLD
@ REF_VEHICLE_OLD
Load/save an old-style reference to a vehicle (for pre-4.4 savegames).
Definition: saveload.h:544
SaveLoadParams::error_str
StringID error_str
the translatable error message to show
Definition: saveload.cpp:210
ChunkHandler::Load
virtual void Load() const =0
Load the chunk.
ZlibSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2655
BSWAP32
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:390
SlSkipHandler::GetDescription
virtual SaveLoadTable GetDescription() const override
Get the description of the fields in the savegame.
Definition: saveload.cpp:1876
SlString
static void SlString(void *ptr, size_t length, VarType conv)
Save/Load a string.
Definition: saveload.cpp:971
GamelogStopAction
void GamelogStopAction()
Stops logging of any changes.
Definition: gamelog.cpp:78
StringValidationSettings
StringValidationSettings
Settings for the string validation.
Definition: string_type.h:49
SlGetStructListLength
size_t SlGetStructListLength(size_t limit)
Get the length of this list; if it exceeds the limit, error out.
Definition: saveload.cpp:1827
SaveLoad::handler
std::shared_ptr< SaveLoadHandler > handler
Custom handler for Save/Load procs.
Definition: saveload.h:668
LoadCheckData::error
StringID error
Error message from loading. INVALID_STRING_ID if no error.
Definition: fios.h:33
GenerateDefaultSaveName
void GenerateDefaultSaveName(char *buf, const char *last)
Fill the buffer with the default name for a savegame or screenshot.
Definition: saveload.cpp:3362
WriteValue
void WriteValue(void *ptr, VarType conv, int64 val)
Write the value of a setting.
Definition: saveload.cpp:830
SL_VECTOR
@ SL_VECTOR
Save/load a vector of SL_VAR elements.
Definition: saveload.h:647
SlCalcVectorLen
static size_t SlCalcVectorLen(const void *vector, VarType conv)
Return the size in bytes of a std::vector.
Definition: saveload.cpp:1519
MemoryDumper::bufe
byte * bufe
End of the buffer we write to.
Definition: saveload.cpp:134
SaveLoadParams::expect_table_header
bool expect_table_header
In the case of a table, if the header is saved/loaded.
Definition: saveload.cpp:202
SL_MAX_VERSION
@ SL_MAX_VERSION
Highest possible saveload version.
Definition: saveload.h:347
SlLoadCheckChunk
static void SlLoadCheckChunk(const ChunkHandler &ch)
Load a chunk of data for checking savegames.
Definition: saveload.cpp:2191
SlError
void NORETURN SlError(StringID string, const char *extra_msg)
Error handler.
Definition: saveload.cpp:334
REF_LINK_GRAPH_JOB
@ REF_LINK_GRAPH_JOB
Load/save a reference to a link graph job.
Definition: saveload.h:551
SlCalcNetStringLen
static size_t SlCalcNetStringLen(const char *ptr, size_t length)
Calculate the net length of a string.
Definition: saveload.cpp:913
ZlibLoadFilter::z
z_stream z
Stream state we are reading from.
Definition: saveload.cpp:2559
LZMALoadFilter::~LZMALoadFilter
~LZMALoadFilter()
Clean everything up.
Definition: saveload.cpp:2700
ReadBuffer::ReadBuffer
ReadBuffer(LoadFilter *reader)
Initialise our variables.
Definition: saveload.cpp:101
DFT_INVALID
@ DFT_INVALID
Unknown or invalid file.
Definition: fileio_type.h:43
_sl
static SaveLoadParams _sl
Parameters used for/at saveload.
Definition: saveload.cpp:217
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
SaveLoadParams::need_length
NeedLength need_length
working in NeedLength (Autolength) mode?
Definition: saveload.cpp:196
SlErrorCorruptFmt
void NORETURN SlErrorCorruptFmt(const char *format,...)
Issue an SlErrorCorrupt with a format string.
Definition: saveload.cpp:378
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
Pool::PoolItem<&_company_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:386
SlStorageHelper::SlCalcLen
static size_t SlCalcLen(const void *storage, VarType conv, SaveLoadType cmd=SL_VAR)
Internal templated helper to return the size in bytes of a list-like type.
Definition: saveload.cpp:1371
GUISettings::threaded_saves
bool threaded_saves
should we do threaded saves?
Definition: settings_type.h:136
FT_NONE
@ FT_NONE
nothing to do
Definition: fileio_type.h:17
FiosNumberedSaveName
A savegame name automatically numbered.
Definition: fios.h:131
REF_ORDERLIST
@ REF_ORDERLIST
Load/save a reference to an orderlist.
Definition: saveload.h:548
SaveLoadParams
The saveload struct, containing reader-writer functions, buffer, version, etc.
Definition: saveload.cpp:194
LZMALoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2705
SlGetFieldLength
size_t SlGetFieldLength()
Get the length of the current object.
Definition: saveload.cpp:794
SlCalcArrayLen
static size_t SlCalcArrayLen(size_t length, VarType conv)
Return the size in bytes of a certain type of atomic array.
Definition: saveload.cpp:1172
DetailedFileType
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:28
LoadCheckData::Clear
void Clear()
Reset read data.
Definition: fios_gui.cpp:48
SlStorageHelper
Template class to help with list-like types.
Definition: saveload.cpp:1362
DoLoad
static SaveOrLoadResult DoLoad(LoadFilter *reader, bool load_check)
Actually perform the loading of a "non-old" savegame.
Definition: saveload.cpp:3081
_saveload_formats
static const SaveLoadFormat _saveload_formats[]
The different saveload formats known/understood by OpenTTD.
Definition: saveload.cpp:2806
FileReader::Reset
void Reset() override
Reset this filter to read from the beginning of the file.
Definition: saveload.cpp:2372
SL_REFLIST
@ SL_REFLIST
Save/load a list of SL_REF elements.
Definition: saveload.h:648
SlErrorCorrupt
void NORETURN SlErrorCorrupt(const char *msg)
Error handler for corrupt savegames.
Definition: saveload.cpp:366
SaveFilter
Interface for filtering a savegame till it is written.
Definition: saveload_filter.h:60
SetAsyncSaveFinish
static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
Called by save thread to tell we finished saving.
Definition: saveload.cpp:399
GetVarMemType
static VarType GetVarMemType(VarType type)
Get the NumberType of a setting.
Definition: saveload.h:1068
SaveLoadParams::action
SaveLoadAction action
are we doing a save or a load atm.
Definition: saveload.cpp:195
endof
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:394
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:63
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:260
SanitizeFilename
void SanitizeFilename(char *filename)
Sanitizes a filename, i.e.
Definition: fileio.cpp:1089
SaveWithFilter
SaveOrLoadResult SaveWithFilter(SaveFilter *writer, bool threaded)
Save the game using a (writer) filter.
Definition: saveload.cpp:3064
SlGetGammaLength
static uint SlGetGammaLength(size_t i)
Return how many bytes used to encode a gamma value.
Definition: saveload.cpp:553
SlReadByte
byte SlReadByte()
Wrapper for reading a byte from the buffer.
Definition: saveload.cpp:426
ZlibSaveFilter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2660
LZOSaveFilter
Filter using LZO compression.
Definition: saveload.cpp:2475
SaveLoadParams::obj_len
size_t obj_len
the length of the current object we are busy with
Definition: saveload.cpp:200
SlSkipHandler::LoadCheck
void LoadCheck(void *object) const override
Similar to load, but used only to validate savegames.
Definition: saveload.cpp:1871
LZMASaveFilter::~LZMASaveFilter
~LZMASaveFilter()
Clean up what we allocated.
Definition: saveload.cpp:2742
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:554
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
SlWriteSimpleGamma
static void SlWriteSimpleGamma(size_t i)
Write the header descriptor of an object or an array.
Definition: saveload.cpp:528
SaveLoad::version_from
SaveLoadVersion version_from
Save/load the variable starting from this savegame version.
Definition: saveload.h:663
LoadCheckData::grf_compatibility
GRFListCompatibility grf_compatibility
Summary state of NewGrfs, whether missing files or only compatible found.
Definition: fios.h:44
SaveOrLoadResult
SaveOrLoadResult
Save or load result codes.
Definition: saveload.h:351
GamelogReset
void GamelogReset()
Resets and frees all memory allocated - used before loading or starting a new game.
Definition: gamelog.cpp:115
WL_ERROR
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition: error.h:24
FiosType
FiosType
Elements of a file system that are recognized.
Definition: fileio_type.h:67
SLE_VAR_STRQ
@ SLE_VAR_STRQ
string pointer enclosed in quotes
Definition: saveload.h:595
SaveLoadParams::saveinprogress
bool saveinprogress
Whether there is currently a save in progress.
Definition: saveload.cpp:214
SaveFilter::chain
SaveFilter * chain
Chained to the (savegame) filters.
Definition: saveload_filter.h:62
SaveLoadParams::game_speed
uint16 game_speed
The game speed when saving started.
Definition: saveload.cpp:213
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
SlSkipHandler::Save
void Save(void *object) const override
Save the object to disk.
Definition: saveload.cpp:1858
SlRefList
static void SlRefList(void *list, VarType conv)
Save/Load a list.
Definition: saveload.cpp:1460
ReadBuffer::read
size_t read
The amount of read bytes so far from the filter.
Definition: saveload.cpp:95
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:171
REF_LINK_GRAPH
@ REF_LINK_GRAPH
Load/save a reference to a link graph.
Definition: saveload.h:550
saveload_internal.h
SLO_INVALID
@ SLO_INVALID
Unknown file operation.
Definition: fileio_type.h:52
SLA_NULL
@ SLA_NULL
null all pointers (on loading error)
Definition: saveload.cpp:76
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
SlStdString
static void SlStdString(void *ptr, VarType conv)
Save/Load a std::string.
Definition: saveload.cpp:1050
SaveLoadFormat::tag
uint32 tag
the 4-letter tag by which it is identified in the savegame
Definition: saveload.cpp:2797
LoadFilter
Interface for filtering a savegame till it is loaded.
Definition: saveload_filter.h:14
Town
Town data structure.
Definition: town.h:50
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
SaveLoadParams::error
bool error
did an error occur or not
Definition: saveload.cpp:198
CargoPacket
Container for cargo from the same location and time.
Definition: cargopacket.h:43
SL_DEQUE
@ SL_DEQUE
Save/load a deque of SL_VAR elements.
Definition: saveload.h:646
SaveLoadParams::dumper
MemoryDumper * dumper
Memory dumper to write the savegame to.
Definition: saveload.cpp:204
FileReader::~FileReader
~FileReader()
Make sure everything is cleaned up.
Definition: saveload.cpp:2355
SLV_SAVELOAD_LIST_LENGTH
@ SLV_SAVELOAD_LIST_LENGTH
293 PR#9374 Consistency in list length with SL_STRUCT / SL_STRUCTLIST / SL_DEQUE / SL_REFLIST.
Definition: saveload.h:335
GetVariableAddress
static void * GetVariableAddress(const void *object, const SaveLoad &sld)
Get the address of the variable.
Definition: saveload.h:1099
GetAbstractFileType
AbstractFileType GetAbstractFileType(FiosType fios_type)
Extract the abstract file type from a FiosType.
Definition: fileio_type.h:90
SlCompatTableHeader
std::vector< SaveLoad > SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
Load a table header in a savegame compatible way.
Definition: saveload.cpp:2031
SlCopyBytes
static void SlCopyBytes(void *ptr, size_t length)
Save/Load bytes.
Definition: saveload.cpp:777
LZOLoadFilter
Filter using LZO compression.
Definition: saveload.cpp:2428
MEMORY_CHUNK_SIZE
static const size_t MEMORY_CHUNK_SIZE
Save in chunks of 128 KiB.
Definition: saveload.cpp:87
ProcessAsyncSaveFinish
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition: saveload.cpp:410
MemoryDumper::blocks
std::vector< byte * > blocks
Buffer with blocks of allocated memory.
Definition: saveload.cpp:132
SaveLoadParams::extra_msg
char * extra_msg
the error message
Definition: saveload.cpp:211
FileReader
Yes, simply reading from a file.
Definition: saveload.cpp:2342
SlFindChunkHandler
static const ChunkHandler * SlFindChunkHandler(uint32 id)
Find the ChunkHandler that will be used for processing the found chunk in the savegame or in memory.
Definition: saveload.cpp:2291
_ttdp_version
uint32 _ttdp_version
version of TTDP savegame (if applicable)
Definition: saveload.cpp:65
ReadValue
int64 ReadValue(const void *ptr, VarType conv)
Return a signed-long version of the value of a setting.
Definition: saveload.cpp:806
SaveLoadParams::last_array_index
int last_array_index
in the case of an array, the current and last positions
Definition: saveload.cpp:201
SlCalcRefLen
static size_t SlCalcRefLen()
Return the size in bytes of a reference (pointer)
Definition: saveload.cpp:655
LZMASaveFilter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2779
_async_save_finish
static std::atomic< AsyncSaveFinishProc > _async_save_finish
Callback to call when the savegame loading is finished.
Definition: saveload.cpp:392
SL_ERROR
@ SL_ERROR
error that was caught before internal structures were modified
Definition: saveload.h:353
FileToSaveLoad::detail_ftype
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:360
Pool::PoolItem<&_orderlist_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:326
WC_STATUS_BAR
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
Definition: window_type.h:57
ReadBuffer::GetSize
size_t GetSize() const
Get the size of the memory dump made so far.
Definition: saveload.cpp:123
RoadStop
A Stop for a Road Vehicle.
Definition: roadstop_base.h:22
FiosNumberedSaveName::Extension
std::string Extension()
Generate an extension for a savegame name.
Definition: fios.cpp:801
SaveLoad::name
std::string name
Name of this field (optional, used for tables).
Definition: saveload.h:659
SlObject
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
Definition: saveload.cpp:1840
ZlibSaveFilter::~ZlibSaveFilter
~ZlibSaveFilter()
Clean up what we allocated.
Definition: saveload.cpp:2615
ChunkHandler::LoadCheck
virtual void LoadCheck(size_t len=0) const
Load the chunk for game preview.
Definition: saveload.cpp:2118
LZMASaveFilter
Filter using LZMA compression.
Definition: saveload.cpp:2728
SLV_START_PATCHPACKS
@ SLV_START_PATCHPACKS
220 First known patchpack to use a version just above ours.
Definition: saveload.h:325
SlTableHeader
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
Definition: saveload.cpp:1893
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:113
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
SlSetStructListLength
void SlSetStructListLength(size_t length)
Set the length of this list.
Definition: saveload.cpp:1811
SlCalcStringLen
static size_t SlCalcStringLen(const void *ptr, size_t length, VarType conv)
Calculate the gross length of the string that it will occupy in the savegame.
Definition: saveload.cpp:928
SLV_4
@ SLV_4
4.0 1 4.1 122 0.3.3, 0.3.4 4.2 1222 0.3.5 4.3 1417 4.4 1426
Definition: saveload.h:41
strecat
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: string.cpp:85
FileToSaveLoad::SetMode
void SetMode(FiosType ft)
Set the mode and file type of the file to save or load based on the type of file entry at the file sy...
Definition: saveload.cpp:3395
SlSkipHandler::GetCompatDescription
virtual SaveLoadCompatTable GetCompatDescription() const override
Get the pre-header description of the fields in the savegame.
Definition: saveload.cpp:1881
SaveLoad
SaveLoad type struct.
Definition: saveload.h:658
Company
Definition: company_base.h:117
LZOSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2486
ClearSaveLoadState
static void ClearSaveLoadState()
Clear/free saveload state.
Definition: saveload.cpp:2901
LoadFilter::chain
LoadFilter * chain
Chained to the (savegame) filters.
Definition: saveload_filter.h:16
LoadFilter::LoadFilter
LoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload_filter.h:22
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
SL_OK
@ SL_OK
completed successfully
Definition: saveload.h:352
SVS_REPLACE_WITH_QUESTION_MARK
@ SVS_REPLACE_WITH_QUESTION_MARK
Replace the unknown/bad bits with question marks.
Definition: string_type.h:51
FiosNumberedSaveName::Filename
std::string Filename()
Generate a savegame name and number according to _settings_client.gui.max_num_autosaves.
Definition: fios.cpp:791
SL_STDSTR
@ SL_STDSTR
Save/load a std::string.
Definition: saveload.h:643
Order
Definition: order_base.h:36
SlSkipBytes
static 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:1146
_lzma_init
static const lzma_stream _lzma_init
Have a copy of an initialised LZMA stream.
Definition: saveload.cpp:2682
SLE_VAR_NAME
@ SLE_VAR_NAME
old custom name to be converted to a char pointer
Definition: saveload.h:596
FileWriter::~FileWriter
~FileWriter()
Make sure everything is cleaned up.
Definition: saveload.cpp:2394
SlCalcObjLength
size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt)
Calculate the size of an object.
Definition: saveload.cpp:1596
_game_speed
uint16 _game_speed
Current game-speed; 100 is 1x, 0 is infinite.
Definition: gfx.cpp:40
SlIterateArray
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition: saveload.cpp:672
SetDParamStr
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:296
FileReader::FileReader
FileReader(FILE *file)
Create the file reader, so it reads from a specific file.
Definition: saveload.cpp:2350
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
SlSaveChunk
static void SlSaveChunk(const ChunkHandler &ch)
Save a chunk of data (eg.
Definition: saveload.cpp:2239
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:601
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:25
FileWriter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2410
FileToSaveLoad::file_op
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:359
FileWriter
Yes, simply writing to a file.
Definition: saveload.cpp:2382
ReadBuffer::bufe
byte * bufe
End of the buffer we can read from.
Definition: saveload.cpp:93
MemoryDumper
Container for dumping the savegame (quickly) to memory.
Definition: saveload.cpp:131
SL_STRUCTLIST
@ SL_STRUCTLIST
Save/load a list of structs.
Definition: saveload.h:649
AllocaM
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132