Freeciv21
Develop your civilization from humble roots to a global empire
savegame2.cpp
Go to the documentation of this file.
1 /*__ ___ ***************************************
2 / \ / \ Copyright (c) 1996-2021 Freeciv21 and Freeciv
3 \_ \ / __/ contributors. This file is part of Freeciv21.
4  _\ \ / /__ Freeciv21 is free software: you can redistribute it
5  \___ \____/ __/ and/or modify it under the terms of the GNU General
6  \_ _/ Public License as published by the Free Software
7  | @ @ \_ Foundation, either version 3 of the License,
8  | or (at your option) any later version.
9  _/ /\ You should have received a copy of the GNU
10  /o) (o/\ \_ General Public License along with Freeciv21.
11  \_____/ / If not, see https://www.gnu.org/licenses/.
12  \____/ ********************************************************/
13 
14 /*
15  This file includes the definition of a new savegame format introduced with
16  2.3.0. It is defined by the mandatory option '+version2'. The main load
17  function checks if this option is present. If not, the old (pre-2.3.0)
18  loading routines are used.
19  The format version is also saved in the settings section of the savefile,
20  as an integer (savefile.version). The integer is used to determine the
21  version of the savefile.
22 
23  Structure of this file:
24 
25  - The real work is done by savegame2_load().
26  This function call all submodules (settings, players, etc.)
27 
28  - The remaining part of this file is split into several sections:
29  * helper functions
30  * load functions for all submodules (and their subsubmodules)
31 
32  - If possible, all functions for load submodules should exit in
33  pairs named sg_load_<submodule>. If one is not
34  needed please add a comment why.
35 
36  - The submodules can be further divided as:
37  sg_load_<submodule>_<subsubmodule>
38 
39  - If needed (due to static variables in the *.c files) these functions
40  can be located in the corresponding source files (as done for the
41  settings and the event_cache).
42 
43  Loading a savegame:
44 
45  - The status of the process is saved within the static variable
46  'sg_success'. This variable is set to TRUE within savegame2_load().
47  If you encounter an error use sg_failure_*() to set it to FALSE and
48  return an error message. Furthermore, sg_check_* should be used at the
49  start of each (submodule) function to return if previous functions
50  failed.
51 
52  - While the loading process dependencies between different modules exits.
53  They can be handled within the struct loaddata *loading which is used as
54  first argument for all sg_load_*() function. Please indicate the
55  dependencies within the definition of this struct.
56 
57 */
58 
59 #include <fc_config.h>
60 
61 #include <QBitArray>
62 
63 #include <cstdarg>
64 #include <cstdio>
65 #include <cstdlib>
66 #include <cstring>
67 #include <sstream>
68 
69 // utility
70 #include "bitvector.h"
71 #include "fcintl.h"
72 #include "idex.h"
73 #include "log.h"
74 #include "rand.h"
75 #include "registry.h"
76 #include "shared.h"
77 #include "support.h" // bool type
78 // common
79 #include "achievements.h"
80 #include "ai.h"
81 #include "capability.h"
82 #include "citizens.h"
83 #include "city.h"
84 #include "game.h"
85 #include "government.h"
86 #include "map.h"
87 #include "mapimg.h"
88 #include "movement.h"
89 #include "multipliers.h"
90 #include "packets.h"
91 #include "research.h"
92 #include "rgbcolor.h"
93 #include "specialist.h"
94 #include "style.h"
95 #include "unit.h"
96 #include "unitlist.h"
97 #include "version.h"
98 
99 // server
100 #include "citizenshand.h"
101 #include "citytools.h"
102 #include "cityturn.h"
103 #include "diplhand.h"
104 #include "maphand.h"
105 #include "meta.h"
106 #include "notify.h"
107 #include "plrhand.h"
108 #include "report.h"
109 #include "ruleset.h"
110 #include "sanitycheck.h"
111 #include "savecompat.h"
112 #include "score.h"
113 #include "settings.h"
114 #include "spacerace.h"
115 #include "srv_main.h"
116 #include "techtools.h"
117 #include "unittools.h"
118 
119 /* server/advisors */
120 #include "advbuilding.h"
121 #include "advdata.h"
122 #include "infracache.h"
123 
124 /* server/generator */
125 #include "mapgen_utils.h"
126 
127 /* server/scripting */
128 #include "script_server.h"
129 
130 // ai
131 #include "aitraits.h"
132 #include "difficulty.h"
133 
134 #include "savegame2.h"
135 
136 extern bool sg_success;
137 
138 /*
139  * This loops over the entire map to save data. It collects all the data of
140  * a line using GET_XY_CHAR and then executes the macro SECFILE_INSERT_LINE.
141  *
142  * Parameters:
143  * ptile: current tile within the line (used by GET_XY_CHAR)
144  * GET_XY_CHAR: macro returning the map character for each position
145  * secfile: a secfile struct
146  * secpath, ...: path as used for sprintf() with arguments; the last item
147  * will be the y coordinate
148  * Example:
149  * SAVE_MAP_CHAR(ptile, terrain2char(ptile->terrain), file, "map.t%04d");
150  */
151 #define SAVE_MAP_CHAR(ptile, GET_XY_CHAR, secfile, secpath, ...) \
152  { \
153  char _line[wld.map.xsize + 1]; \
154  int _nat_x, _nat_y; \
155  \
156  for (_nat_y = 0; _nat_y < wld.map.ysize; _nat_y++) { \
157  for (_nat_x = 0; _nat_x < wld.map.xsize; _nat_x++) { \
158  struct tile *ptile = \
159  native_pos_to_tile(&(wld.map), _nat_x, _nat_y); \
160  fc_assert_action(ptile != nullptr, continue); \
161  _line[_nat_x] = (GET_XY_CHAR); \
162  sg_failure_ret(QChar::isPrint(_line[_nat_x] & 0x7f), \
163  "Trying to write invalid map data at position " \
164  "(%d, %d) for path %s: '%c' (%d)", \
165  _nat_x, _nat_y, secpath, _line[_nat_x], \
166  _line[_nat_x]); \
167  } \
168  _line[wld.map.xsize] = '\0'; \
169  secfile_insert_str(secfile, _line, secpath, ##__VA_ARGS__, _nat_y); \
170  } \
171  }
172 
173 /*
174  * This loops over the entire map to load data. It inputs a line of data
175  * using the macro SECFILE_LOOKUP_LINE and then loops using the macro
176  * SET_XY_CHAR to load each char into the map at (map_x, map_y). Internal
177  * variables ch, map_x, map_y, nat_x, and nat_y are allocated within the
178  * macro but definable by the caller.
179  *
180  * Parameters:
181  * ch: a variable to hold a char (data for a single position,
182  * used by SET_XY_CHAR)
183  * ptile: current tile within the line (used by SET_XY_CHAR)
184  * SET_XY_CHAR: macro to load the map character at each (map_x, map_y)
185  * secfile: a secfile struct
186  * secpath, ...: path as used for sprintf() with arguments; the last item
187  * will be the y coordinate
188  * Example:
189  * LOAD_MAP_CHAR(ch, ptile,
190  * map_get_player_tile(ptile, plr)->terrain
191  * = char2terrain(ch), file, "player%d.map_t%04d", plrno);
192  *
193  * Note: some (but not all) of the code this is replacing used to skip over
194  * lines that did not exist. This allowed for backward-compatibility.
195  * We could add another parameter that specified whether it was OK to
196  * skip the data, but there's not really much advantage to exiting
197  * early in this case. Instead, we let any map data type to be empty,
198  * and just print an informative warning message about it.
199  */
200 #define LOAD_MAP_CHAR(ch, ptile, SET_XY_CHAR, secfile, secpath, ...) \
201  { \
202  int _nat_x, _nat_y; \
203  bool _printed_warning = false; \
204  for (_nat_y = 0; _nat_y < wld.map.ysize; _nat_y++) { \
205  const char *_line = \
206  secfile_lookup_str(secfile, secpath, ##__VA_ARGS__, _nat_y); \
207  if (nullptr == _line) { \
208  char buf[64]; \
209  fc_snprintf(buf, sizeof(buf), secpath, ##__VA_ARGS__, _nat_y); \
210  qDebug("Line not found='%s'", buf); \
211  _printed_warning = true; \
212  continue; \
213  } else if (strlen(_line) != wld.map.xsize) { \
214  char buf[64]; \
215  fc_snprintf(buf, sizeof(buf), secpath, ##__VA_ARGS__, _nat_y); \
216  qDebug("Line too short (expected %d got %lu)='%s'", wld.map.xsize, \
217  (unsigned long) qstrlen(_line), buf); \
218  _printed_warning = true; \
219  continue; \
220  } \
221  for (_nat_x = 0; _nat_x < wld.map.xsize; _nat_x++) { \
222  const char ch = _line[_nat_x]; \
223  struct tile *ptile = \
224  native_pos_to_tile(&(wld.map), _nat_x, _nat_y); \
225  (SET_XY_CHAR); \
226  } \
227  } \
228  if (_printed_warning) { \
229  /* TRANS: Minor error message. */ \
230  log_sg(_("Saved game contains incomplete map data. This can" \
231  " happen with old saved games, or it may indicate an" \
232  " invalid saved game file. Proceed at your own risk.")); \
233  } \
234  }
235 
236 // Iterate on the extras half-bytes
237 #define halfbyte_iterate_extras(e, num_extras_types) \
238  { \
239  int e; \
240  for (e = 0; 4 * e < (num_extras_types); e++) {
241 
242 #define halfbyte_iterate_extras_end \
243  } \
244  }
245 
246 // Iterate on the specials half-bytes
247 #define halfbyte_iterate_special(s, num_specials_types) \
248  { \
249  int s; \
250  for (s = 0; 4 * s < (num_specials_types); s++) {
251 
252 #define halfbyte_iterate_special_end \
253  } \
254  }
255 
256 // Iterate on the bases half-bytes
257 #define halfbyte_iterate_bases(b, num_bases_types) \
258  { \
259  int b; \
260  for (b = 0; 4 * b < (num_bases_types); b++) {
261 
262 #define halfbyte_iterate_bases_end \
263  } \
264  }
265 
266 // Iterate on the roads half-bytes
267 #define halfbyte_iterate_roads(r, num_roads_types) \
268  { \
269  int r; \
270  for (r = 0; 4 * r < (num_roads_types); r++) {
271 
272 #define halfbyte_iterate_roads_end \
273  } \
274  }
275 
276 #define TOKEN_SIZE 10
277 
278 static struct loaddata *loaddata_new(struct section_file *file);
279 static void loaddata_destroy(struct loaddata *loading);
280 
281 static enum unit_orders char2order(char order);
282 static enum direction8 char2dir(char dir);
283 static char activity2char(enum unit_activity activity);
284 static enum unit_activity char2activity(char activity);
285 static int unquote_block(const char *const quoted_, void *dest,
286  int dest_length);
287 static void worklist_load(struct section_file *file, struct worklist *pwl,
288  const char *path, ...);
289 static void unit_ordering_apply();
290 static void sg_extras_set(bv_extras *extras, char ch,
291  struct extra_type **idx);
292 static void sg_special_set(struct tile *ptile, bv_extras *extras, char ch,
293  const enum tile_special_type *idx,
294  bool rivers_overlay);
295 static void sg_bases_set(bv_extras *extras, char ch, struct base_type **idx);
296 static void sg_roads_set(bv_extras *extras, char ch, struct road_type **idx);
297 static struct extra_type *char2resource(char c);
298 static struct terrain *char2terrain(char ch);
299 static Tech_type_id technology_load(struct section_file *file,
300  const char *path, int plrno);
301 
302 static void sg_load_ruleset(struct loaddata *loading);
303 static void sg_load_savefile(struct loaddata *loading);
304 
305 static void sg_load_game(struct loaddata *loading);
306 
307 static void sg_load_ruledata(struct loaddata *loading);
308 
309 static void sg_load_random(struct loaddata *loading);
310 
311 static void sg_load_script(struct loaddata *loading);
312 
313 static void sg_load_scenario(struct loaddata *loading);
314 
315 static void sg_load_settings(struct loaddata *loading);
316 
317 static void sg_load_map(struct loaddata *loading);
318 static void sg_load_map_tiles(struct loaddata *loading);
319 static void sg_load_map_tiles_extras(struct loaddata *loading);
320 static void sg_load_map_tiles_bases(struct loaddata *loading);
321 static void sg_load_map_tiles_roads(struct loaddata *loading);
322 static void sg_load_map_tiles_specials(struct loaddata *loading,
323  bool rivers_overlay);
324 static void sg_load_map_tiles_resources(struct loaddata *loading);
325 
326 static void sg_load_map_startpos(struct loaddata *loading);
327 static void sg_load_map_owner(struct loaddata *loading);
328 static void sg_load_map_worked(struct loaddata *loading);
329 static void sg_load_map_known(struct loaddata *loading);
330 
331 static void sg_load_players_basic(struct loaddata *loading);
332 static void sg_load_players(struct loaddata *loading);
333 static void sg_load_player_main(struct loaddata *loading,
334  struct player *plr);
335 static void sg_load_player_cities(struct loaddata *loading,
336  struct player *plr);
337 static bool sg_load_player_city(struct loaddata *loading, struct player *plr,
338  struct city *pcity, const char *citystr);
339 static void sg_load_player_city_citizens(struct loaddata *loading,
340  struct player *plr,
341  struct city *pcity,
342  const char *citystr);
343 static void sg_load_player_units(struct loaddata *loading,
344  struct player *plr);
345 static bool sg_load_player_unit(struct loaddata *loading, struct player *plr,
346  struct unit *punit, const char *unitstr);
347 static void sg_load_player_units_transport(struct loaddata *loading,
348  struct player *plr);
349 static void sg_load_player_attributes(struct loaddata *loading,
350  struct player *plr);
351 static void sg_load_player_vision(struct loaddata *loading,
352  struct player *plr);
353 static bool sg_load_player_vision_city(struct loaddata *loading,
354  struct player *plr,
355  struct vision_site *pdcity,
356  const char *citystr);
357 
358 static void sg_load_researches(struct loaddata *loading);
359 
360 static void sg_load_event_cache(struct loaddata *loading);
361 
362 static void sg_load_treaties(struct loaddata *loading);
363 
364 static void sg_load_history(struct loaddata *loading);
365 
366 static void sg_load_mapimg(struct loaddata *loading);
367 
368 static void sg_load_sanitycheck(struct loaddata *loading);
369 
370 /* =======================================================================
371  * Basic load / save functions.
372  * ======================================================================= */
373 
377 void savegame2_load(struct section_file *file)
378 {
379  struct loaddata *loading;
380  bool was_send_city_suppressed, was_send_tile_suppressed;
381 
382  // initialise loading
383  was_send_city_suppressed = send_city_suppression(true);
384  was_send_tile_suppressed = send_tile_suppression(true);
385  loading = loaddata_new(file);
386  sg_success = true;
387 
388  // Load the savegame data.
389  // Set up correct ruleset
390  sg_load_ruleset(loading);
391  // [compat]
392  sg_load_compat(loading, SAVEGAME_2);
393  // [savefile]
394  sg_load_savefile(loading);
395  // [game]
396  sg_load_game(loading);
397  // [scenario]
398  sg_load_scenario(loading);
399  // [random]
400  sg_load_random(loading);
401  // [settings]
402  sg_load_settings(loading);
403  // [ruledata]
404  sg_load_ruledata(loading);
405  // [players] (basic data)
406  sg_load_players_basic(loading);
407  // [map]; needs width and height loaded by [settings]
408  sg_load_map(loading);
409  // [research]
410  sg_load_researches(loading);
411  // [player<i>]
412  sg_load_players(loading);
413  // [event_cache]
414  sg_load_event_cache(loading);
415  // [treaties]
416  sg_load_treaties(loading);
417  // [history]
418  sg_load_history(loading);
419  // [mapimg]
420  sg_load_mapimg(loading);
421  // [script] -- must come last as may reference game objects
422  sg_load_script(loading);
423  // [post_load_compat]; needs the game loaded by [savefile]
425 
426  // Sanity checks for the loaded game.
427  sg_load_sanitycheck(loading);
428 
429  // deinitialise loading
430  loaddata_destroy(loading);
431  send_tile_suppression(was_send_tile_suppressed);
432  send_city_suppression(was_send_city_suppressed);
433 
434  if (!sg_success) {
435  qCritical("Failure loading savegame!");
436  // Try to get the server back to a vaguely sane state
438  server_game_init(false);
439  load_rulesets(nullptr, nullptr, false, nullptr, true, false, true);
440  }
441 }
442 
446 static struct loaddata *loaddata_new(struct section_file *file)
447 {
448  struct loaddata *loading = new loaddata{};
449  loading->file = file;
450  loading->secfile_options = nullptr;
451 
452  loading->improvement.order = nullptr;
453  loading->improvement.size = -1;
454  loading->technology.order = nullptr;
455  loading->technology.size = -1;
456  loading->activities.order = nullptr;
457  loading->activities.size = -1;
458  loading->trait.order = nullptr;
459  loading->trait.size = -1;
460  loading->extra.order = nullptr;
461  loading->extra.size = -1;
462  loading->multiplier.order = nullptr;
463  loading->multiplier.size = -1;
464  loading->special.order = nullptr;
465  loading->special.size = -1;
466  loading->base.order = nullptr;
467  loading->base.size = -1;
468  loading->road.order = nullptr;
469  loading->road.size = -1;
470  loading->specialist.order = nullptr;
471  loading->specialist.size = -1;
472  loading->ds_t.order = nullptr;
473  loading->ds_t.size = -1;
474 
475  loading->server_state = S_S_INITIAL;
476  loading->rstate = fc_rand_state();
477  loading->worked_tiles = nullptr;
478 
479  return loading;
480 }
481 
485 static void loaddata_destroy(struct loaddata *loading)
486 {
487  delete[] loading->improvement.order;
488  delete[] loading->technology.order;
489  delete[] loading->activities.order;
490  delete[] loading->trait.order;
491  delete[] loading->extra.order;
492  delete[] loading->multiplier.order;
493  delete[] loading->special.order;
494  delete[] loading->base.order;
495  delete[] loading->road.order;
496  delete[] loading->specialist.order;
497  delete[] loading->ds_t.order;
498  delete[] loading->worked_tiles;
499  delete loading;
500  loading = nullptr;
501 }
502 
503 /* =======================================================================
504  * Helper functions.
505  * ======================================================================= */
506 
510 static enum unit_orders char2order(char order)
511 {
512  switch (order) {
513  case 'm':
514  case 'M':
515  return ORDER_MOVE;
516  case 'w':
517  case 'W':
518  return ORDER_FULL_MP;
519  case 'b':
520  case 'B':
521  return static_cast<unit_orders>(ORDER_OLD_BUILD_CITY);
522  case 'a':
523  case 'A':
524  return ORDER_ACTIVITY;
525  case 'd':
526  case 'D':
527  return static_cast<unit_orders>(ORDER_OLD_DISBAND);
528  case 'u':
529  case 'U':
530  return static_cast<unit_orders>(ORDER_OLD_BUILD_WONDER);
531  case 't':
532  case 'T':
533  return static_cast<unit_orders>(ORDER_OLD_TRADE_ROUTE);
534  case 'h':
535  case 'H':
536  return static_cast<unit_orders>(ORDER_OLD_HOMECITY);
537  case 'x':
538  case 'X':
539  return ORDER_ACTION_MOVE;
540  }
541 
542  // This can happen if the savegame is invalid.
543  return ORDER_LAST;
544 }
545 
549 static enum direction8 char2dir(char dir)
550 {
551  // Numberpad values for the directions.
552  switch (dir) {
553  case '1':
554  return DIR8_SOUTHWEST;
555  case '2':
556  return DIR8_SOUTH;
557  case '3':
558  return DIR8_SOUTHEAST;
559  case '4':
560  return DIR8_WEST;
561  case '6':
562  return DIR8_EAST;
563  case '7':
564  return DIR8_NORTHWEST;
565  case '8':
566  return DIR8_NORTH;
567  case '9':
568  return DIR8_NORTHEAST;
569  }
570 
571  // This can happen if the savegame is invalid.
572  return direction8_invalid();
573 }
574 
578 static char activity2char(enum unit_activity activity)
579 {
580  switch (activity) {
581  case ACTIVITY_IDLE:
582  return 'w';
583  case ACTIVITY_POLLUTION:
584  return 'p';
585  case ACTIVITY_OLD_ROAD:
586  return 'r';
587  case ACTIVITY_MINE:
588  return 'm';
589  case ACTIVITY_IRRIGATE:
590  return 'i';
591  case ACTIVITY_FORTIFIED:
592  return 'f';
593  case ACTIVITY_FORTRESS:
594  return 't';
595  case ACTIVITY_SENTRY:
596  return 's';
597  case ACTIVITY_OLD_RAILROAD:
598  return 'l';
599  case ACTIVITY_PILLAGE:
600  return 'e';
601  case ACTIVITY_GOTO:
602  return 'g';
603  case ACTIVITY_EXPLORE:
604  return 'x';
605  case ACTIVITY_TRANSFORM:
606  return 'o';
607  case ACTIVITY_AIRBASE:
608  return 'a';
609  case ACTIVITY_FORTIFYING:
610  return 'y';
611  case ACTIVITY_FALLOUT:
612  return 'u';
613  case ACTIVITY_BASE:
614  return 'b';
615  case ACTIVITY_GEN_ROAD:
616  return 'R';
617  case ACTIVITY_CONVERT:
618  return 'c';
619  case ACTIVITY_UNKNOWN:
620  case ACTIVITY_PATROL_UNUSED:
621  case ACTIVITY_CULTIVATE:
622  case ACTIVITY_PLANT:
623  return '?';
624  case ACTIVITY_LAST:
625  break;
626  }
627 
628  fc_assert(false);
629  return '?';
630 }
631 
635 static enum unit_activity char2activity(char activity)
636 {
637  int a;
638 
639  for (a = 0; a < ACTIVITY_LAST; a++) {
640  char achar = activity2char(static_cast<unit_activity>(a));
641 
642  if (activity == achar) {
643  return static_cast<unit_activity>(a);
644  }
645  }
646 
647  // This can happen if the savegame is invalid.
648  return ACTIVITY_LAST;
649 }
650 
656 static int unquote_block(const char *const quoted_, void *dest,
657  int dest_length)
658 {
659  int i, length, parsed, tmp;
660  char *endptr;
661  const char *quoted = quoted_;
662 
663  parsed = sscanf(quoted, "%d", &length);
664  fc_assert_ret_val(1 == parsed, 0);
665 
666  if (length > dest_length) {
667  return 0;
668  }
669  quoted = strchr(quoted, ':');
670  fc_assert_ret_val(quoted != nullptr, 0);
671  quoted++;
672 
673  for (i = 0; i < length; i++) {
674  tmp = strtol(quoted, &endptr, 16);
675  fc_assert_ret_val((endptr - quoted) == 2, 0);
676  fc_assert_ret_val(*endptr == ' ', 0);
677  fc_assert_ret_val((tmp & 0xff) == tmp, 0);
678  (static_cast<unsigned char *>(dest))[i] = tmp;
679  quoted += 3;
680  }
681  return length;
682 }
683 
688 static void worklist_load(struct section_file *file, struct worklist *pwl,
689  const char *path, ...)
690 {
691  int i;
692  const char *kind;
693  const char *name;
694  char path_str[1024];
695  va_list ap;
696 
697  /* The first part of the registry path is taken from the varargs to the
698  * function. */
699  va_start(ap, path);
700  fc_vsnprintf(path_str, sizeof(path_str), path, ap);
701  va_end(ap);
702 
703  worklist_init(pwl);
704  pwl->length =
705  secfile_lookup_int_default(file, 0, "%s.wl_length", path_str);
706 
707  for (i = 0; i < pwl->length; i++) {
708  kind = secfile_lookup_str(file, "%s.wl_kind%d", path_str, i);
709 
710  /* We lookup the production value by name. An invalid entry isn't a
711  * fatal error; we just truncate the worklist. */
712  name =
713  secfile_lookup_str_default(file, "-", "%s.wl_value%d", path_str, i);
714  pwl->entries[i] = universal_by_rule_name(kind, name);
715  if (pwl->entries[i].kind == universals_n_invalid()) {
716  log_sg("%s.wl_value%d: unknown \"%s\" \"%s\".", path_str, i, kind,
717  name);
718  pwl->length = i;
719  break;
720  }
721  }
722 }
723 
728 static void unit_ordering_apply()
729 {
730  players_iterate(pplayer)
731  {
732  city_list_iterate(pplayer->cities, pcity)
733  {
734  unit_list_sort_ord_city(pcity->units_supported);
735  }
737  }
739 
740  whole_map_iterate(&(wld.map), ptile)
741  {
742  unit_list_sort_ord_map(ptile->units);
743  }
745 }
746 
754 static void sg_extras_set(bv_extras *extras, char ch,
755  struct extra_type **idx)
756 {
757  int i, bin;
758  const char *pch = strchr(hex_chars, ch);
759 
760  if (!pch || ch == '\0') {
761  log_sg("Unknown hex value: '%c' (%d)", ch, ch);
762  bin = 0;
763  } else {
764  bin = pch - hex_chars;
765  }
766 
767  for (i = 0; i < 4; i++) {
768  struct extra_type *pextra = idx[i];
769 
770  if (pextra == nullptr) {
771  continue;
772  }
773  if ((bin & (1 << i))
774  && (wld.map.server.have_huts
775  || !is_extra_caused_by(pextra, EC_HUT))) {
776  BV_SET(*extras, extra_index(pextra));
777  }
778  }
779 }
780 
788 static void sg_special_set(struct tile *ptile, bv_extras *extras, char ch,
789  const enum tile_special_type *idx,
790  bool rivers_overlay)
791 {
792  int i, bin;
793  const char *pch = strchr(hex_chars, ch);
794 
795  if (!pch || ch == '\0') {
796  log_sg("Unknown hex value: '%c' (%d)", ch, ch);
797  bin = 0;
798  } else {
799  bin = pch - hex_chars;
800  }
801 
802  for (i = 0; i < 4; i++) {
803  enum tile_special_type sp = idx[i];
804 
805  if (sp == S_LAST) {
806  continue;
807  }
808  if (rivers_overlay && sp != S_OLD_RIVER) {
809  continue;
810  }
811 
812  if (sp == S_HUT && !wld.map.server.have_huts) {
813  /* It would be logical to have this in the saving side -
814  * really not saving the huts in the first place, BUT
815  * 1) They have been saved by older versions, so we
816  * have to deal with such savegames.
817  * 2) This makes scenario author less likely to lose
818  * one's work completely after carefully placing huts
819  * and then saving with 'have_huts' disabled. */
820  continue;
821  }
822 
823  if (bin & (1 << i)) {
824  if (sp == S_OLD_ROAD) {
825  struct road_type *proad;
826 
828  if (proad) {
830  }
831  } else if (sp == S_OLD_RAILROAD) {
832  struct road_type *proad;
833 
835  if (proad) {
837  }
838  } else if (sp == S_OLD_RIVER) {
839  struct road_type *proad;
840 
842  if (proad) {
844  }
845  } else {
846  struct extra_type *pextra = nullptr;
847  enum extra_cause cause = EC_COUNT;
848 
849  /* Converting from old hardcoded specials to as sensible extra as we
850  * can */
851  switch (sp) {
852  case S_IRRIGATION:
853  case S_FARMLAND:
854  /* If old savegame has both irrigation and farmland, EC_IRRIGATION
855  * gets applied twice, which hopefully has the correct result. */
856  cause = EC_IRRIGATION;
857  break;
858  case S_MINE:
859  cause = EC_MINE;
860  break;
861  case S_POLLUTION:
862  cause = EC_POLLUTION;
863  break;
864  case S_HUT:
865  cause = EC_HUT;
866  break;
867  case S_FALLOUT:
868  cause = EC_FALLOUT;
869  break;
870  default:
872  break;
873  }
874 
875  if (cause != EC_COUNT) {
876  struct tile *vtile = tile_virtual_new(ptile);
877  struct terrain *pterr = tile_terrain(vtile);
878 
879  /* Do not let the extras already set to the real tile mess with
880  * setup of the player tiles if that's what we're doing. */
881  vtile->extras = *extras;
882 
883  /* It's ok not to know which player or which unit originally built
884  * the extra - in the rules used when specials were saved these
885  * could not have made any difference. */
886  /* Can't use next_extra_for_tile() as it works for buildable extras
887  * only. */
888  if ((cause != EC_IRRIGATION || pterr->irrigation_result == pterr)
889  && (cause != EC_MINE || pterr->mining_result == pterr)
890  && (cause != EC_BASE || pterr->base_time != 0)
891  && (cause != EC_ROAD || pterr->road_time != 0)) {
892  extra_type_by_cause_iterate(cause, candidate)
893  {
894  if (!tile_has_extra(vtile, candidate)) {
895  if ((!is_extra_caused_by(candidate, EC_BASE)
896  || tile_city(vtile) != nullptr
897  || extra_base_get(candidate)->border_sq <= 0)
898  && are_reqs_active(nullptr, tile_owner(vtile), nullptr,
899  nullptr, vtile, nullptr, nullptr,
900  nullptr, nullptr, nullptr,
901  &candidate->reqs, RPT_POSSIBLE)) {
902  pextra = candidate;
903  break;
904  }
905  }
906  }
908  }
909 
910  tile_virtual_destroy(vtile);
911  }
912 
913  if (pextra) {
914  BV_SET(*extras, extra_index(pextra));
915  }
916  }
917  }
918  }
919 }
920 
928 static void sg_bases_set(bv_extras *extras, char ch, struct base_type **idx)
929 {
930  int i, bin;
931  const char *pch = strchr(hex_chars, ch);
932 
933  if (!pch || ch == '\0') {
934  log_sg("Unknown hex value: '%c' (%d)", ch, ch);
935  bin = 0;
936  } else {
937  bin = pch - hex_chars;
938  }
939 
940  for (i = 0; i < 4; i++) {
941  struct base_type *pbase = idx[i];
942 
943  if (pbase == nullptr) {
944  continue;
945  }
946  if (bin & (1 << i)) {
948  }
949  }
950 }
951 
959 static void sg_roads_set(bv_extras *extras, char ch, struct road_type **idx)
960 {
961  int i, bin;
962  const char *pch = strchr(hex_chars, ch);
963 
964  if (!pch || ch == '\0') {
965  log_sg("Unknown hex value: '%c' (%d)", ch, ch);
966  bin = 0;
967  } else {
968  bin = pch - hex_chars;
969  }
970 
971  for (i = 0; i < 4; i++) {
972  struct road_type *proad = idx[i];
973 
974  if (proad == nullptr) {
975  continue;
976  }
977  if (bin & (1 << i)) {
979  }
980  }
981 }
982 
986 static struct extra_type *char2resource(char c)
987 {
988  // speed common values
990  return nullptr;
991  }
992 
993  return resource_by_identifier(c);
994 }
995 
1000 static struct terrain *char2terrain(char ch)
1001 {
1002  // terrain_by_identifier plus fatal error
1003  if (ch == TERRAIN_UNKNOWN_IDENTIFIER) {
1004  return T_UNKNOWN;
1005  }
1006  terrain_type_iterate(pterrain)
1007  {
1008  if (pterrain->identifier == ch) {
1009  return pterrain;
1010  }
1011  }
1013 
1014  qFatal("Unknown terrain identifier '%c' in savegame.", ch);
1015  exit(EXIT_FAILURE);
1016 }
1017 
1023  const char *path, int plrno)
1024 {
1025  char path_with_name[128];
1026  const char *name;
1027  struct advance *padvance;
1028 
1029  fc_snprintf(path_with_name, sizeof(path_with_name), "%s_name", path);
1030 
1031  name = secfile_lookup_str(file, path_with_name, plrno);
1032 
1033  if (!name || name[0] == '\0') {
1034  // used by researching_saved
1035  return A_UNKNOWN;
1036  }
1037  if (fc_strcasecmp(name, "A_FUTURE") == 0) {
1038  return A_FUTURE;
1039  }
1040  if (fc_strcasecmp(name, "A_NONE") == 0) {
1041  return A_NONE;
1042  }
1043  if (fc_strcasecmp(name, "A_UNSET") == 0) {
1044  return A_UNSET;
1045  }
1046 
1047  padvance = advance_by_rule_name(name);
1048  sg_failure_ret_val(nullptr != padvance, A_NONE,
1049  "%s: unknown technology \"%s\".", path_with_name, name);
1050 
1051  return advance_number(padvance);
1052 }
1053 
1054 /* =======================================================================
1055  * Load savefile data.
1056  * ======================================================================= */
1057 
1061 static void sg_load_ruleset(struct loaddata *loading)
1062 {
1063  const char *ruleset = secfile_lookup_str_default(
1064  loading->file, GAME_DEFAULT_RULESETDIR, "savefile.rulesetdir");
1065 
1066  // Load ruleset.
1067  sz_strlcpy(game.server.rulesetdir, ruleset);
1068  if (!strcmp("default", game.server.rulesetdir)) {
1069  int version;
1070 
1071  version =
1072  secfile_lookup_int_default(loading->file, -1, "savefile.version");
1073  if (version >= 30) {
1074  /* Here 'default' really means current default.
1075  * Saving happens with real ruleset name, so savegames containing this
1076  * are special scenarios. */
1078  } else {
1079  // 'default' is the old name of the classic ruleset
1080  sz_strlcpy(game.server.rulesetdir, "classic");
1081  }
1082  qDebug("Savegame specified ruleset '%s'. Really loading '%s'.", ruleset,
1083  game.server.rulesetdir);
1084  }
1085  if (!load_rulesets(nullptr, nullptr, false, nullptr, true, false, true)) {
1086  // Failed to load correct ruleset
1087  sg_failure_ret(false,
1088  _("Failed to load ruleset '%s' needed for savegame."),
1089  ruleset);
1090  }
1091 }
1092 
1096 static void sg_load_savefile(struct loaddata *loading)
1097 {
1098  int i;
1099  const char *terr_name;
1100 
1101  // Check status and return if not OK (sg_success != TRUE).
1102  sg_check_ret();
1103 
1104  // Load savefile options.
1105  loading->secfile_options =
1106  secfile_lookup_str(loading->file, "savefile.options");
1107 
1108  /* We don't need these entries, but read them anyway to avoid
1109  * warnings about unread secfile entries. */
1110  (void) secfile_entry_by_path(loading->file, "savefile.reason");
1111  (void) secfile_entry_by_path(loading->file, "savefile.revision");
1112 
1113  /* In case of savegame2.c saves, missing entry means savegame older than
1114  * support for saving last_updated by turn. So this must default to TRUE.
1115  */
1116  game.server.last_updated_year = secfile_lookup_bool_default(
1117  loading->file, true, "savefile.last_updated_as_year");
1118 
1119  // Load improvements.
1121  loading->file, 0, "savefile.improvement_size");
1122  if (loading->improvement.size) {
1123  loading->improvement.order =
1124  secfile_lookup_str_vec(loading->file, &loading->improvement.size,
1125  "savefile.improvement_vector");
1126  sg_failure_ret(loading->improvement.size != 0,
1127  "Failed to load improvement order: %s", secfile_error());
1128  }
1129 
1130  // Load technologies.
1132  loading->file, 0, "savefile.technology_size");
1133  if (loading->technology.size) {
1134  loading->technology.order =
1135  secfile_lookup_str_vec(loading->file, &loading->technology.size,
1136  "savefile.technology_vector");
1137  sg_failure_ret(loading->technology.size != 0,
1138  "Failed to load technology order: %s", secfile_error());
1139  }
1140 
1141  // Load Activities.
1143  loading->file, 0, "savefile.activities_size");
1144  if (loading->activities.size) {
1145  loading->activities.order =
1146  secfile_lookup_str_vec(loading->file, &loading->activities.size,
1147  "savefile.activities_vector");
1148  sg_failure_ret(loading->activities.size != 0,
1149  "Failed to load activity order: %s", secfile_error());
1150  }
1151 
1152  // Load traits.
1153  loading->trait.size =
1154  secfile_lookup_int_default(loading->file, 0, "savefile.trait_size");
1155  if (loading->trait.size) {
1156  loading->trait.order = secfile_lookup_str_vec(
1157  loading->file, &loading->trait.size, "savefile.trait_vector");
1158  sg_failure_ret(loading->trait.size != 0,
1159  "Failed to load trait order: %s", secfile_error());
1160  }
1161 
1162  // Load extras.
1163  loading->extra.size =
1164  secfile_lookup_int_default(loading->file, 0, "savefile.extras_size");
1165  if (loading->extra.size) {
1166  const char **modname;
1167  size_t nmod;
1168  int j;
1169 
1170  modname = secfile_lookup_str_vec(loading->file, &loading->extra.size,
1171  "savefile.extras_vector");
1172  sg_failure_ret(loading->extra.size != 0,
1173  "Failed to load extras order: %s", secfile_error());
1174  sg_failure_ret(!(game.control.num_extra_types < loading->extra.size),
1175  "Number of extras defined by the ruleset (= %d) are "
1176  "lower than the number in the savefile (= %d).",
1177  game.control.num_extra_types, (int) loading->extra.size);
1178  // make sure that the size of the array is divisible by 4
1179  nmod = 4 * ((loading->extra.size + 3) / 4);
1180  loading->extra.order = new extra_type *[nmod]();
1181  for (j = 0; j < loading->extra.size; j++) {
1182  loading->extra.order[j] = extra_type_by_rule_name(modname[j]);
1183  }
1184  delete[] modname;
1185  for (; j < nmod; j++) {
1186  loading->extra.order[j] = nullptr;
1187  }
1188  }
1189 
1190  // Load multipliers.
1192  loading->file, 0, "savefile.multipliers_size");
1193  if (loading->multiplier.size) {
1194  const char **modname;
1195  int j;
1196 
1197  modname =
1198  secfile_lookup_str_vec(loading->file, &loading->multiplier.size,
1199  "savefile.multipliers_vector");
1200  sg_failure_ret(loading->multiplier.size != 0,
1201  "Failed to load multipliers order: %s", secfile_error());
1202  /* It's OK for the set of multipliers in the savefile to differ
1203  * from those in the ruleset. */
1204  loading->multiplier.order = new multiplier *[loading->multiplier.size]();
1205  for (j = 0; j < loading->multiplier.size; j++) {
1206  loading->multiplier.order[j] = multiplier_by_rule_name(modname[j]);
1207  if (!loading->multiplier.order[j]) {
1208  qDebug("Multiplier \"%s\" in savegame but not in ruleset, "
1209  "discarding",
1210  modname[j]);
1211  }
1212  }
1213  delete[] modname;
1214  }
1215 
1216  // Load specials.
1217  loading->special.size =
1218  secfile_lookup_int_default(loading->file, 0, "savefile.specials_size");
1219  if (loading->special.size) {
1220  const char **modname;
1221  size_t nmod;
1222  int j;
1223 
1224  modname = secfile_lookup_str_vec(loading->file, &loading->special.size,
1225  "savefile.specials_vector");
1226  sg_failure_ret(loading->special.size != 0,
1227  "Failed to load specials order: %s", secfile_error());
1228  // make sure that the size of the array is divisible by 4
1229  /* Allocating extra 4 slots, just a couple of bytes,
1230  * in case of special.size being divisible by 4 already is intentional.
1231  * Added complexity would cost those couple of bytes in code size alone,
1232  * and we actually need at least one slot immediately after last valid
1233  * one. That's where S_LAST is (or was in version that saved the game)
1234  * and in some cases S_LAST gets written to savegame, at least as
1235  * activity target special when activity targets some base or road
1236  * instead. By having current S_LAST in that index allows us to map
1237  * that old S_LAST to current S_LAST, just like any real special within
1238  * special.size gets mapped. */
1239  nmod = loading->special.size + (4 - (loading->special.size % 4));
1240  loading->special.order = new tile_special_type[nmod]();
1241  for (j = 0; j < loading->special.size; j++) {
1242  if (!fc_strcasecmp("Road", modname[j])) {
1243  loading->special.order[j] = S_OLD_ROAD;
1244  } else if (!fc_strcasecmp("Railroad", modname[j])) {
1245  loading->special.order[j] = S_OLD_RAILROAD;
1246  } else if (!fc_strcasecmp("River", modname[j])) {
1247  loading->special.order[j] = S_OLD_RIVER;
1248  } else {
1249  loading->special.order[j] = special_by_rule_name(modname[j]);
1250  }
1251  }
1252  delete[] modname;
1253  for (; j < nmod; j++) {
1254  loading->special.order[j] = S_LAST;
1255  }
1256  }
1257 
1258  // Load bases.
1259  loading->base.size =
1260  secfile_lookup_int_default(loading->file, 0, "savefile.bases_size");
1261  if (loading->base.size) {
1262  const char **modname;
1263  size_t nmod;
1264  int j;
1265 
1266  modname = secfile_lookup_str_vec(loading->file, &loading->base.size,
1267  "savefile.bases_vector");
1268  sg_failure_ret(loading->base.size != 0, "Failed to load bases order: %s",
1269  secfile_error());
1270  // make sure that the size of the array is divisible by 4
1271  nmod = 4 * ((loading->base.size + 3) / 4);
1272  loading->base.order = new base_type *[nmod]();
1273  for (j = 0; j < loading->base.size; j++) {
1274  struct extra_type *pextra = extra_type_by_rule_name(modname[j]);
1275 
1276  sg_failure_ret(pextra != nullptr
1277  || game.control.num_base_types
1278  >= loading->base.size,
1279  "Unknown base type %s in savefile.", modname[j]);
1280 
1281  if (pextra != nullptr) {
1282  loading->base.order[j] = extra_base_get(pextra);
1283  } else {
1284  loading->base.order[j] = nullptr;
1285  }
1286  }
1287  delete[] modname;
1288  for (; j < nmod; j++) {
1289  loading->base.order[j] = nullptr;
1290  }
1291  }
1292 
1293  // Load roads.
1294  loading->road.size =
1295  secfile_lookup_int_default(loading->file, 0, "savefile.roads_size");
1296  if (loading->road.size) {
1297  const char **modname;
1298  size_t nmod;
1299  int j;
1300 
1301  modname = secfile_lookup_str_vec(loading->file, &loading->road.size,
1302  "savefile.roads_vector");
1303  sg_failure_ret(loading->road.size != 0, "Failed to load roads order: %s",
1304  secfile_error());
1305  sg_failure_ret(!(game.control.num_road_types < loading->road.size),
1306  "Number of roads defined by the ruleset (= %d) are "
1307  "lower than the number in the savefile (= %d).",
1308  game.control.num_road_types, (int) loading->road.size);
1309  // make sure that the size of the array is divisible by 4
1310  nmod = 4 * ((loading->road.size + 3) / 4);
1311  loading->road.order = new road_type *[nmod]();
1312  for (j = 0; j < loading->road.size; j++) {
1313  struct extra_type *pextra = extra_type_by_rule_name(modname[j]);
1314 
1315  if (pextra != nullptr) {
1316  loading->road.order[j] = extra_road_get(pextra);
1317  } else {
1318  loading->road.order[j] = nullptr;
1319  }
1320  }
1321  delete[] modname;
1322  for (; j < nmod; j++) {
1323  loading->road.order[j] = nullptr;
1324  }
1325  }
1326 
1327  // Load specialists.
1329  loading->file, 0, "savefile.specialists_size");
1330  if (loading->specialist.size) {
1331  const char **modname;
1332  size_t nmod;
1333  int j;
1334 
1335  modname =
1336  secfile_lookup_str_vec(loading->file, &loading->specialist.size,
1337  "savefile.specialists_vector");
1338  sg_failure_ret(loading->specialist.size != 0,
1339  "Failed to load specialists order: %s", secfile_error());
1341  !(game.control.num_specialist_types < loading->specialist.size),
1342  "Number of specialists defined by the ruleset (= %d) are "
1343  "lower than the number in the savefile (= %d).",
1344  game.control.num_specialist_types, (int) loading->specialist.size);
1345  // make sure that the size of the array is divisible by 4
1346  /* That's not really needed with specialists at the moment, but done this
1347  * way for consistency with other types, and to be prepared for the time
1348  * it needs to be this way. */
1349  nmod = 4 * ((loading->specialist.size + 3) / 4);
1350  loading->specialist.order = new specialist *[nmod]();
1351  for (j = 0; j < loading->specialist.size; j++) {
1352  loading->specialist.order[j] = specialist_by_rule_name(modname[j]);
1353  }
1354  delete[] modname;
1355  for (; j < nmod; j++) {
1356  loading->specialist.order[j] = nullptr;
1357  }
1358  }
1359 
1360  // Load diplomatic state type order.
1362  loading->file, 0, "savefile.diplstate_type_size");
1363 
1364  sg_failure_ret(loading->ds_t.size > 0,
1365  "Failed to load diplomatic state type order: %s",
1366  secfile_error());
1367 
1368  if (loading->ds_t.size) {
1369  const char **modname;
1370  int j;
1371 
1372  modname = secfile_lookup_str_vec(loading->file, &loading->ds_t.size,
1373  "savefile.diplstate_type_vector");
1374 
1375  loading->ds_t.order = new diplstate_type[loading->ds_t.size]();
1376 
1377  for (j = 0; j < loading->ds_t.size; j++) {
1378  loading->ds_t.order[j] =
1379  diplstate_type_by_name(modname[j], fc_strcasecmp);
1380  }
1381 
1382  delete[] modname;
1383  }
1384 
1385  terrain_type_iterate(pterr) { pterr->identifier_load = '\0'; }
1387 
1388  i = 0;
1389  while ((terr_name = secfile_lookup_str_default(
1390  loading->file, nullptr, "savefile.terrident%d.name", i))
1391  != nullptr) {
1392  struct terrain *pterr = terrain_by_rule_name(terr_name);
1393 
1394  if (pterr != nullptr) {
1395  const char *iptr = secfile_lookup_str_default(
1396  loading->file, nullptr, "savefile.terrident%d.identifier", i);
1397 
1398  pterr->identifier_load = *iptr;
1399  } else {
1400  qCritical("Identifier for unknown terrain type %s.", terr_name);
1401  }
1402  i++;
1403  }
1404 
1405  terrain_type_iterate(pterr)
1406  {
1407  terrain_type_iterate(pterr2)
1408  {
1409  if (pterr != pterr2 && pterr->identifier_load != '\0') {
1410  sg_failure_ret((pterr->identifier_load != pterr2->identifier_load),
1411  "%s and %s share a saved identifier",
1412  terrain_rule_name(pterr), terrain_rule_name(pterr2));
1413  }
1414  }
1416  }
1418 }
1419 
1420 /* =======================================================================
1421  * Load game status.
1422  * ======================================================================= */
1423 
1427 static void sg_load_ruledata(struct loaddata *loading)
1428 {
1429  int i;
1430  const char *name;
1431 
1432  // Check status and return if not OK (sg_success != TRUE).
1433  sg_check_ret();
1434 
1435  for (i = 0; (name = secfile_lookup_str_default(
1436  loading->file, nullptr, "ruledata.government%d.name", i));
1437  i++) {
1438  struct government *gov = government_by_rule_name(name);
1439 
1440  if (gov != nullptr) {
1442  loading->file, 0, "ruledata.government%d.changes", i);
1443  }
1444  }
1445 }
1446 
1450 static void sg_load_game(struct loaddata *loading)
1451 {
1452  int game_version;
1453  const char *string;
1454  const char *level;
1455  int i;
1456 
1457  // Check status and return if not OK (sg_success != TRUE).
1458  sg_check_ret();
1459 
1460  // Load version.
1461  game_version =
1462  secfile_lookup_int_default(loading->file, 0, "game.version");
1463  // We require at least version 2.2.99
1464  sg_failure_ret(20299 <= game_version, "Saved game is too old, at least "
1465  "version 2.2.99 required.");
1466 
1467  // Load server state.
1468  string = secfile_lookup_str_default(loading->file, "S_S_INITIAL",
1469  "game.server_state");
1470  loading->server_state = server_states_by_name(string, strcmp);
1471  if (!server_states_is_valid(loading->server_state)) {
1472  // Don't take any risk!
1473  loading->server_state = S_S_INITIAL;
1474  }
1475 
1476  string = secfile_lookup_str_default(
1477  loading->file, default_meta_patches_string(), "game.meta_patches");
1478  set_meta_patches_string(string);
1479 
1480  if (srvarg.metaserver_addr == QLatin1String(DEFAULT_META_SERVER_ADDR)) {
1481  /* Do not overwrite this if the user requested a specific metaserver
1482  * from the command line (option --Metaserver). */
1484  loading->file, DEFAULT_META_SERVER_ADDR, "game.meta_server"));
1485  }
1486 
1487  if (srvarg.serverid.isEmpty()) {
1488  /* Do not overwrite this if the user requested a specific metaserver
1489  * from the command line (option --serverid). */
1490  srvarg.serverid = QString::fromUtf8(
1491  secfile_lookup_str_default(loading->file, "", "game.serverid"));
1492  }
1493  sz_strlcpy(server.game_identifier,
1494  secfile_lookup_str_default(loading->file, "", "game.id"));
1495  /* We are not checking game_identifier legality just yet.
1496  * That's done when we are sure that rand seed has been initialized,
1497  * so that we can generate new game_identifier, if needed.
1498  * See sq_load_sanitycheck(). */
1499 
1500  level = secfile_lookup_str_default(loading->file, nullptr, "game.level");
1501  if (level != nullptr) {
1502  game.info.skill_level = ai_level_by_name(level, fc_strcasecmp);
1503  } else {
1504  game.info.skill_level = ai_level_invalid();
1505  }
1506 
1507  if (!ai_level_is_valid(static_cast<ai_level>(game.info.skill_level))) {
1510  "game.skill_level"));
1511  }
1512  game.info.phase_mode =
1513  static_cast<phase_mode_type>(secfile_lookup_int_default(
1514  loading->file, GAME_DEFAULT_PHASE_MODE, "game.phase_mode"));
1515  game.server.phase_mode_stored = secfile_lookup_int_default(
1516  loading->file, GAME_DEFAULT_PHASE_MODE, "game.phase_mode_stored");
1517  game.info.phase =
1518  secfile_lookup_int_default(loading->file, 0, "game.phase");
1520  loading->file, game.info.turn + GAME_DEFAULT_SCORETURN,
1521  "game.scoreturn");
1522 
1523  game.server.timeoutint = secfile_lookup_int_default(
1524  loading->file, GAME_DEFAULT_TIMEOUTINT, "game.timeoutint");
1525  game.server.timeoutintinc = secfile_lookup_int_default(
1526  loading->file, GAME_DEFAULT_TIMEOUTINTINC, "game.timeoutintinc");
1527  game.server.timeoutinc = secfile_lookup_int_default(
1528  loading->file, GAME_DEFAULT_TIMEOUTINC, "game.timeoutinc");
1529  game.server.timeoutincmult = secfile_lookup_int_default(
1530  loading->file, GAME_DEFAULT_TIMEOUTINCMULT, "game.timeoutincmult");
1531  game.server.timeoutcounter = secfile_lookup_int_default(
1532  loading->file, GAME_DEFAULT_TIMEOUTCOUNTER, "game.timeoutcounter");
1533 
1534  game.info.turn = secfile_lookup_int_default(loading->file, 0, "game.turn");
1536  secfile_lookup_int(loading->file, &game.info.year, "game.year"), "%s",
1537  secfile_error());
1538  game.info.year_0_hack =
1539  secfile_lookup_bool_default(loading->file, false, "game.year_0_hack");
1540 
1541  game.info.globalwarming =
1542  secfile_lookup_int_default(loading->file, 0, "game.globalwarming");
1543  game.info.heating =
1544  secfile_lookup_int_default(loading->file, 0, "game.heating");
1545  game.info.warminglevel =
1546  secfile_lookup_int_default(loading->file, 0, "game.warminglevel");
1547 
1548  game.info.nuclearwinter =
1549  secfile_lookup_int_default(loading->file, 0, "game.nuclearwinter");
1550  game.info.cooling =
1551  secfile_lookup_int_default(loading->file, 0, "game.cooling");
1552  game.info.coolinglevel =
1553  secfile_lookup_int_default(loading->file, 0, "game.coolinglevel");
1554 
1555  // Global advances.
1556  string = secfile_lookup_str_default(loading->file, nullptr,
1557  "game.global_advances");
1558  if (string != nullptr) {
1559  sg_failure_ret(strlen(string) == loading->technology.size,
1560  "Invalid length of 'game.global_advances' (%lu ~= %lu).",
1561  (unsigned long) qstrlen(string),
1562  (unsigned long) loading->technology.size);
1563  for (i = 0; i < loading->technology.size; i++) {
1564  sg_failure_ret(string[i] == '1' || string[i] == '0',
1565  "Undefined value '%c' within 'game.global_advances'.",
1566  string[i]);
1567  if (string[i] == '1') {
1568  struct advance *padvance =
1569  advance_by_rule_name(loading->technology.order[i]);
1570 
1571  if (padvance != nullptr) {
1572  game.info.global_advances[advance_number(padvance)] = true;
1573  }
1574  }
1575  }
1576  }
1577 
1578  game.info.is_new_game =
1579  !secfile_lookup_bool_default(loading->file, true, "game.save_players");
1580 
1581  game.server.turn_change_time =
1582  secfile_lookup_int_default(loading->file, 0,
1583  "game.last_turn_change_time")
1584  / 100;
1585 }
1586 
1587 /* =======================================================================
1588  * Load random status.
1589  * ======================================================================= */
1590 
1594 static void sg_load_random(struct loaddata *loading)
1595 {
1596  // Check status and return if not OK (sg_success != TRUE).
1597  sg_check_ret();
1598 
1599  if (secfile_lookup_bool_default(loading->file, false, "random.saved")) {
1600  /* Since random state was previously saved, save it also when resaving.
1601  * This affects only pre-2.6 scenarios where scenario.save_random
1602  * is not defined.
1603  * - If this is 2.6 or later scenario -> it would have saved random.saved
1604  * = TRUE only if scenario.save_random is already TRUE
1605  *
1606  * Do NOT touch this in case of regular savegame. They always have
1607  * random.saved set, but if one starts to make scenario based on a
1608  * savegame, we want default scenario settings in the beginning (default
1609  * save_random = FALSE).
1610  */
1611  if (game.scenario.is_scenario) {
1612  game.scenario.save_random = true;
1613  }
1614 
1615  if (secfile_lookup_int(loading->file, nullptr, "random.index_J")) {
1616  qWarning().noquote() << QString::fromUtf8(
1617  _("Cannot load old random generator state. Seeding a new one."));
1618  fc_rand_seed(loading->rstate);
1619  } else if (auto *state =
1620  secfile_lookup_str(loading->file, "random.state")) {
1621  // In theory this doesn't exist in old saves, but why not.
1622  std::stringstream ss;
1623  ss.imbue(std::locale::classic());
1624  ss.str(state);
1625  ss >> loading->rstate;
1626  if (ss.fail()) {
1627  qWarning().noquote() << QString::fromUtf8(
1628  _("Cannot load the random generator state. Seeding a new one."));
1629  fc_rand_seed(loading->rstate);
1630  }
1631  }
1632  fc_rand_set_state(loading->rstate);
1633  } else {
1634  // No random values - mark the setting.
1635  (void) secfile_entry_by_path(loading->file, "random.saved");
1636 
1637  /* We're loading a game without a seed (which is okay, if it's a
1638  * scenario). We need to generate the game seed now because it will be
1639  * needed later during the load. */
1640  init_game_seed();
1641  loading->rstate = fc_rand_state();
1642  }
1643 }
1644 
1645 /* =======================================================================
1646  * Load lua script data.
1647  * ======================================================================= */
1648 
1652 static void sg_load_script(struct loaddata *loading)
1653 {
1654  // Check status and return if not OK (sg_success != TRUE).
1655  sg_check_ret();
1656 
1657  script_server_state_load(loading->file);
1658 }
1659 
1660 /* =======================================================================
1661  * Load scenario data.
1662  * ======================================================================= */
1663 
1667 static void sg_load_scenario(struct loaddata *loading)
1668 {
1669  const char *buf;
1670  bool lake_flood_default;
1671 
1672  // Check status and return if not OK (sg_success != TRUE).
1673  sg_check_ret();
1674 
1675  if (nullptr == secfile_section_lookup(loading->file, "scenario")) {
1676  game.scenario.is_scenario = false;
1677 
1678  return;
1679  }
1680 
1681  /* Default is that when there's scenario section (which we already checked)
1682  * this is a scenario. Only if it explicitly says that it's not, we
1683  * consider this regular savegame */
1685  loading->file, true, "scenario.is_scenario");
1686 
1687  if (!game.scenario.is_scenario) {
1688  return;
1689  }
1690 
1691  buf = secfile_lookup_str_default(loading->file, "", "scenario.name");
1692  if (buf[0] != '\0') {
1693  sz_strlcpy(game.scenario.name, buf);
1694  }
1695 
1696  buf = secfile_lookup_str_default(loading->file, "", "scenario.authors");
1697  if (buf[0] != '\0') {
1698  sz_strlcpy(game.scenario.authors, buf);
1699  } else {
1700  game.scenario.authors[0] = '\0';
1701  }
1702 
1703  buf =
1704  secfile_lookup_str_default(loading->file, "", "scenario.description");
1705  if (buf[0] != '\0') {
1706  sz_strlcpy(game.scenario_desc.description, buf);
1707  } else {
1708  game.scenario_desc.description[0] = '\0';
1709  }
1710 
1712  loading->file, false, "scenario.save_random");
1713  game.scenario.players =
1714  secfile_lookup_bool_default(loading->file, true, "scenario.players");
1715  game.scenario.startpos_nations = secfile_lookup_bool_default(
1716  loading->file, false, "scenario.startpos_nations");
1717 
1718  game.scenario.prevent_new_cities = secfile_lookup_bool_default(
1719  loading->file, false, "scenario.prevent_new_cities");
1720  if (loading->version < 20599) {
1721  /* Lake flooding may break some old scenarios where rivers made out of
1722  * lake terrains, so play safe there */
1723  lake_flood_default = false;
1724  } else {
1725  /* If lake flooding is a problem for a newer scenario, it could
1726  * explicitly disable it. */
1727  lake_flood_default = true;
1728  }
1729  game.scenario.lake_flooding = secfile_lookup_bool_default(
1730  loading->file, lake_flood_default, "scenario.lake_flooding");
1731  game.scenario.handmade =
1732  secfile_lookup_bool_default(loading->file, false, "scenario.handmade");
1733  game.scenario.allow_ai_type_fallback = secfile_lookup_bool_default(
1734  loading->file, false, "scenario.allow_ai_type_fallback");
1735  game.scenario.ruleset_locked = true;
1736 
1737  sg_failure_ret(loading->server_state == S_S_INITIAL
1738  || (loading->server_state == S_S_RUNNING
1739  && game.scenario.players == true),
1740  "Invalid scenario definition (server state '%s' and "
1741  "players are %s).",
1742  server_states_name(loading->server_state),
1743  game.scenario.players ? "saved" : "not saved");
1744 
1745  /* Remove all defined players. They are recreated with the skill level
1746  * defined by the scenario. */
1747  (void) aifill(0);
1748 }
1749 
1750 /* =======================================================================
1751  * Load game settings.
1752  * ======================================================================= */
1753 
1757 static void sg_load_settings(struct loaddata *loading)
1758 {
1759  // Check status and return if not OK (sg_success != TRUE).
1760  sg_check_ret();
1761 
1762  settings_game_load(loading->file, "settings");
1763 
1764  // Save current status of fogofwar.
1765  game.server.fogofwar_old = game.info.fogofwar;
1766 
1767  // Add all compatibility settings here.
1768 }
1769 
1770 /* =======================================================================
1771  * Load the main map.
1772  * ======================================================================= */
1773 
1777 static void sg_load_map(struct loaddata *loading)
1778 {
1779  // Check status and return if not OK (sg_success != TRUE).
1780  sg_check_ret();
1781 
1782  /* This defaults to TRUE even if map has not been generated. Also,
1783  * old versions have also explicitly saved TRUE even in pre-game.
1784  * We rely on that
1785  * 1) scenario maps have it explicitly right.
1786  * 2) when map is actually generated, it re-initialize this to FALSE. */
1787  wld.map.server.have_huts =
1788  secfile_lookup_bool_default(loading->file, true, "map.have_huts");
1789 
1790  if (S_S_INITIAL == loading->server_state
1791  && MAPGEN_SCENARIO == wld.map.server.generator) {
1792  /* Generator MAPGEN_SCENARIO is used;
1793  * this map was done with the map editor. */
1794 
1795  // Load tiles.
1796  sg_load_map_tiles(loading);
1797  sg_load_map_startpos(loading);
1798 
1799  if (loading->version >= 30) {
1800  // 2.6.0 or newer
1801  sg_load_map_tiles_extras(loading);
1802  } else {
1803  sg_load_map_tiles_bases(loading);
1804  if (loading->version >= 20) {
1805  // 2.5.0 or newer
1806  sg_load_map_tiles_roads(loading);
1807  }
1808  if (has_capability("specials", loading->secfile_options)) {
1809  // Load specials.
1810  sg_load_map_tiles_specials(loading, false);
1811  }
1812  }
1813 
1814  // have_resources TRUE only if set so by sg_load_map_tiles_resources()
1815  game.scenario.have_resources = false;
1816  if (has_capability("specials", loading->secfile_options)) {
1817  // Load resources.
1818  sg_load_map_tiles_resources(loading);
1819  } else if (has_capability("riversoverlay", loading->secfile_options)) {
1820  // Load only rivers overlay.
1821  sg_load_map_tiles_specials(loading, true);
1822  }
1823 
1824  // Nothing more needed for a scenario.
1825  return;
1826  }
1827 
1828  if (S_S_INITIAL == loading->server_state) {
1829  // Nothing more to do if it is not a scenario but in initial state.
1830  return;
1831  }
1832 
1833  sg_load_map_tiles(loading);
1834  sg_load_map_startpos(loading);
1835  if (loading->version >= 30) {
1836  // 2.6.0 or newer
1837  sg_load_map_tiles_extras(loading);
1838  } else {
1839  sg_load_map_tiles_bases(loading);
1840  if (loading->version >= 20) {
1841  // 2.5.0 or newer
1842  sg_load_map_tiles_roads(loading);
1843  }
1844  sg_load_map_tiles_specials(loading, false);
1845  }
1846  sg_load_map_tiles_resources(loading);
1847  sg_load_map_known(loading);
1848  sg_load_map_owner(loading);
1849  sg_load_map_worked(loading);
1850 }
1851 
1855 static void sg_load_map_tiles(struct loaddata *loading)
1856 {
1857  // Check status and return if not OK (sg_success != TRUE).
1858  sg_check_ret();
1859 
1860  /* Initialize the map for the current topology. 'map.xsize' and
1861  * 'map.ysize' must be set. */
1863 
1864  // Allocate map.
1866 
1867  // get the terrain type
1868  LOAD_MAP_CHAR(ch, ptile, ptile->terrain = char2terrain(ch), loading->file,
1869  "map.t%04d");
1871 
1872  // Check for special tile sprites.
1873  whole_map_iterate(&(wld.map), ptile)
1874  {
1875  const char *spec_sprite;
1876  const char *label;
1877  int nat_x, nat_y;
1878 
1880  spec_sprite = secfile_lookup_str(loading->file, "map.spec_sprite_%d_%d",
1881  nat_x, nat_y);
1882  label = secfile_lookup_str_default(loading->file, nullptr,
1883  "map.label_%d_%d", nat_x, nat_y);
1884  if (nullptr != ptile->spec_sprite) {
1885  ptile->spec_sprite = fc_strdup(spec_sprite);
1886  }
1887  if (label != nullptr) {
1888  tile_set_label(ptile, label);
1889  }
1890  }
1892 }
1893 
1897 static void sg_load_map_tiles_extras(struct loaddata *loading)
1898 {
1899  // Check status and return if not OK (sg_success != TRUE).
1900  sg_check_ret();
1901 
1902  // Load extras.
1903  halfbyte_iterate_extras(j, loading->extra.size)
1904  {
1905  LOAD_MAP_CHAR(
1906  ch, ptile,
1907  sg_extras_set(&ptile->extras, ch, loading->extra.order + 4 * j),
1908  loading->file, "map.e%02d_%04d", j);
1909  }
1911 }
1912 
1916 static void sg_load_map_tiles_bases(struct loaddata *loading)
1917 {
1918  // Check status and return if not OK (sg_success != TRUE).
1919  sg_check_ret();
1920 
1921  // Load bases.
1922  halfbyte_iterate_bases(j, loading->base.size)
1923  {
1924  LOAD_MAP_CHAR(
1925  ch, ptile,
1926  sg_bases_set(&ptile->extras, ch, loading->base.order + 4 * j),
1927  loading->file, "map.b%02d_%04d", j);
1928  }
1930 }
1931 
1935 static void sg_load_map_tiles_roads(struct loaddata *loading)
1936 {
1937  // Check status and return if not OK (sg_success != TRUE).
1938  sg_check_ret();
1939 
1940  // Load roads.
1941  halfbyte_iterate_roads(j, loading->road.size)
1942  {
1943  LOAD_MAP_CHAR(
1944  ch, ptile,
1945  sg_roads_set(&ptile->extras, ch, loading->road.order + 4 * j),
1946  loading->file, "map.r%02d_%04d", j);
1947  }
1949 }
1950 
1954 static void sg_load_map_tiles_specials(struct loaddata *loading,
1955  bool rivers_overlay)
1956 {
1957  // Check status and return if not OK (sg_success != TRUE).
1958  sg_check_ret();
1959 
1960  /* If 'rivers_overlay' is set to TRUE, load only the rivers overlay map
1961  * from the savegame file.
1962  *
1963  * A scenario may define the terrain of the map but not list the specials
1964  * on it (thus allowing users to control the placement of specials).
1965  * However rivers are a special case and must be included in the map along
1966  * with the scenario. Thus in those cases this function should be called
1967  * to load the river information separate from any other special data.
1968  *
1969  * This does not need to be called from map_load(), because map_load()
1970  * loads the rivers overlay along with the rest of the specials. Call this
1971  * only if you've already called map_load_tiles(), and want to load only
1972  * the rivers overlay but no other specials. Scenarios that encode things
1973  * this way should have the "riversoverlay" capability. */
1975  {
1976  LOAD_MAP_CHAR(ch, ptile,
1977  sg_special_set(ptile, &ptile->extras, ch,
1978  loading->special.order + 4 * j,
1979  rivers_overlay),
1980  loading->file, "map.spe%02d_%04d", j);
1981  }
1983 }
1984 
1988 static void sg_load_map_tiles_resources(struct loaddata *loading)
1989 {
1990  // Check status and return if not OK (sg_success != TRUE).
1991  sg_check_ret();
1992 
1993  LOAD_MAP_CHAR(ch, ptile, tile_set_resource(ptile, char2resource(ch)),
1994  loading->file, "map.res%04d");
1995 
1996  // After the resources are loaded, indicate those currently valid.
1997  whole_map_iterate(&(wld.map), ptile)
1998  {
1999  if (nullptr == ptile->resource) {
2000  continue;
2001  }
2002 
2003  if (ptile->terrain == nullptr
2004  || !terrain_has_resource(ptile->terrain, ptile->resource)) {
2005  BV_CLR(ptile->extras, extra_index(ptile->resource));
2006  }
2007  }
2009 
2010  wld.map.server.have_resources = true;
2011  game.scenario.have_resources = true;
2012 }
2013 
2018 static void sg_load_map_startpos(struct loaddata *loading)
2019 {
2020  struct nation_type *pnation;
2021  struct startpos *psp;
2022  struct tile *ptile;
2023  const char SEPARATOR = '#';
2024  const char *nation_names;
2025  int nat_x, nat_y;
2026  bool exclude;
2027  int i, startpos_count;
2028 
2029  // Check status and return if not OK (sg_success != TRUE).
2030  sg_check_ret();
2031 
2032  startpos_count =
2033  secfile_lookup_int_default(loading->file, 0, "map.startpos_count");
2034 
2035  if (0 == startpos_count) {
2036  // Nothing to do.
2037  return;
2038  }
2039 
2040  for (i = 0; i < startpos_count; i++) {
2041  if (!secfile_lookup_int(loading->file, &nat_x, "map.startpos%d.x", i)
2042  || !secfile_lookup_int(loading->file, &nat_y, "map.startpos%d.y",
2043  i)) {
2044  log_sg("Warning: Undefined coordinates for startpos %d", i);
2045  continue;
2046  }
2047 
2048  ptile = native_pos_to_tile(&(wld.map), nat_x, nat_y);
2049  if (nullptr == ptile) {
2050  qCritical("Start position native coordinates (%d, %d) do not exist "
2051  "in this map. Skipping...",
2052  nat_x, nat_y);
2053  continue;
2054  }
2055 
2056  exclude = secfile_lookup_bool_default(loading->file, false,
2057  "map.startpos%d.exclude", i);
2058 
2059  psp = map_startpos_new(ptile);
2060 
2061  nation_names =
2062  secfile_lookup_str(loading->file, "map.startpos%d.nations", i);
2063  if (nullptr != nation_names && '\0' != nation_names[0]) {
2064  const size_t size = qstrlen(nation_names) + 1;
2065  char buf[size], *start, *end;
2066 
2067  memcpy(buf, nation_names, size);
2068  for (start = buf - 1; nullptr != start; start = end) {
2069  start++;
2070  if ((end = strchr(start, SEPARATOR))) {
2071  *end = '\0';
2072  }
2073 
2074  pnation = nation_by_rule_name(start);
2075  if (NO_NATION_SELECTED != pnation) {
2076  if (exclude) {
2077  startpos_disallow(psp, pnation);
2078  } else {
2079  startpos_allow(psp, pnation);
2080  }
2081  } else {
2082  qDebug("Missing nation \"%s\".", start);
2083  }
2084  }
2085  }
2086  }
2087 
2088  if (0 < map_startpos_count() && loading->server_state == S_S_INITIAL
2089  && map_startpos_count() < game.server.max_players) {
2090  qDebug("Number of starts (%d) are lower than rules.max_players "
2091  "(%d), lowering rules.max_players.",
2092  map_startpos_count(), game.server.max_players);
2093  game.server.max_players = map_startpos_count();
2094  }
2095 
2096  /* Re-initialize nation availability in light of start positions.
2097  * This has to be after loading [scenario] and [map].startpos and
2098  * before we seek nations for players. */
2100 }
2101 
2105 static void sg_load_map_owner(struct loaddata *loading)
2106 {
2107  int x, y;
2108  struct player *owner = nullptr;
2109  struct tile *claimer = nullptr;
2110  struct player *eowner = nullptr;
2111 
2112  // Check status and return if not OK (sg_success != TRUE).
2113  sg_check_ret();
2114 
2115  if (game.info.is_new_game) {
2116  /* No owner/source information for a new game / scenario. */
2117  return;
2118  }
2119 
2120  // Owner and ownership source are stored as plain numbers
2121  for (y = 0; y < wld.map.ysize; y++) {
2122  const char *buffer1 =
2123  secfile_lookup_str(loading->file, "map.owner%04d", y);
2124  const char *buffer2 =
2125  secfile_lookup_str(loading->file, "map.source%04d", y);
2126  const char *buffer3 =
2127  secfile_lookup_str(loading->file, "map.eowner%04d", y);
2128  const char *ptr1 = buffer1;
2129  const char *ptr2 = buffer2;
2130  const char *ptr3 = buffer3;
2131 
2132  sg_failure_ret(buffer1 != nullptr, "%s", secfile_error());
2133  sg_failure_ret(buffer2 != nullptr, "%s", secfile_error());
2134  if (loading->version >= 30) {
2135  sg_failure_ret(buffer3 != nullptr, "%s", secfile_error());
2136  }
2137 
2138  for (x = 0; x < wld.map.xsize; x++) {
2139  char token1[TOKEN_SIZE];
2140  char token2[TOKEN_SIZE];
2141  char token3[TOKEN_SIZE];
2142  int number;
2143  struct tile *ptile = native_pos_to_tile(&(wld.map), x, y);
2144  char n[] = ",";
2145  scanin(const_cast<char **>(&ptr1), n, token1, sizeof(token1));
2146  sg_failure_ret(token1[0] != '\0',
2147  "Map size not correct (map.owner%d).", y);
2148  if (strcmp(token1, "-") == 0) {
2149  owner = nullptr;
2150  } else {
2151  sg_failure_ret(str_to_int(token1, &number),
2152  "Got map owner %s in (%d, %d).", token1, x, y);
2153  owner = player_by_number(number);
2154  }
2155  scanin(const_cast<char **>(&ptr2), n, token2, sizeof(token2));
2156  sg_failure_ret(token2[0] != '\0',
2157  "Map size not correct (map.source%d).", y);
2158  if (strcmp(token2, "-") == 0) {
2159  claimer = nullptr;
2160  } else {
2161  sg_failure_ret(str_to_int(token2, &number),
2162  "Got map source %s in (%d, %d).", token2, x, y);
2163  claimer = index_to_tile(&(wld.map), number);
2164  }
2165 
2166  if (loading->version >= 30) {
2167  char n[] = ",";
2168  scanin(const_cast<char **>(&ptr3), n, token3, sizeof(token3));
2169  sg_failure_ret(token3[0] != '\0',
2170  "Map size not correct (map.eowner%d).", y);
2171  if (strcmp(token3, "-") == 0) {
2172  eowner = nullptr;
2173  } else {
2174  sg_failure_ret(str_to_int(token3, &number),
2175  "Got base owner %s in (%d, %d).", token3, x, y);
2176  eowner = player_by_number(number);
2177  }
2178  } else {
2179  eowner = owner;
2180  }
2181 
2182  map_claim_ownership(ptile, owner, claimer, false);
2183  tile_claim_bases(ptile, eowner);
2184  log_debug("extras_owner(%d, %d) = %s", TILE_XY(ptile),
2185  player_name(eowner));
2186  }
2187  }
2188 }
2189 
2193 static void sg_load_map_worked(struct loaddata *loading)
2194 {
2195  int x, y;
2196 
2197  // Check status and return if not OK (sg_success != TRUE).
2198  sg_check_ret();
2199 
2200  sg_failure_ret(loading->worked_tiles == nullptr,
2201  "City worked map not loaded!");
2202 
2203  loading->worked_tiles = new int[MAP_INDEX_SIZE];
2204 
2205  for (y = 0; y < wld.map.ysize; y++) {
2206  const char *buffer =
2207  secfile_lookup_str(loading->file, "map.worked%04d", y);
2208  const char *ptr = buffer;
2209 
2210  sg_failure_ret(nullptr != buffer,
2211  "Savegame corrupt - map line %d not found.", y);
2212  for (x = 0; x < wld.map.xsize; x++) {
2213  char token[TOKEN_SIZE];
2214  int number;
2215  struct tile *ptile = native_pos_to_tile(&(wld.map), x, y);
2216  char n[] = ",";
2217  scanin(const_cast<char **>(&ptr), n, token, sizeof(token));
2218  sg_failure_ret('\0' != token[0],
2219  "Savegame corrupt - map size not correct.");
2220  if (strcmp(token, "-") == 0) {
2221  number = -1;
2222  } else {
2223  sg_failure_ret(str_to_int(token, &number) && 0 < number,
2224  "Savegame corrupt - got tile worked by city "
2225  "id=%s in (%d, %d).",
2226  token, x, y);
2227  }
2228 
2229  loading->worked_tiles[ptile->index] = number;
2230  }
2231  }
2232 }
2233 
2237 static void sg_load_map_known(struct loaddata *loading)
2238 {
2239  // Check status and return if not OK (sg_success != TRUE).
2240  sg_check_ret();
2241 
2242  players_iterate(pplayer)
2243  {
2244  /* Allocate player private map here; it is needed in different modules
2245  * besides this one ((i.e. sg_load_player_*()). */
2246  player_map_init(pplayer);
2247  }
2249 
2250  if (secfile_lookup_bool_default(loading->file, true, "game.save_known")) {
2251  int lines = player_slot_max_used_number() / 32 + 1, j, p, l, i;
2252  unsigned int *known = new unsigned int[lines * MAP_INDEX_SIZE]();
2253 
2254  for (l = 0; l < lines; l++) {
2255  for (j = 0; j < 8; j++) {
2256  for (i = 0; i < 4; i++) {
2257  /* Only bother trying to load the map for this halfbyte if at least
2258  * one of the corresponding player slots is in use. */
2259  if (player_slot_is_used(
2260  player_slot_by_number(l * 32 + j * 4 + i))) {
2261  LOAD_MAP_CHAR(ch, ptile,
2262  known[l * MAP_INDEX_SIZE + tile_index(ptile)] |=
2263  ascii_hex2bin(ch, j),
2264  loading->file, "map.k%02d_%04d", l * 8 + j);
2265  break;
2266  }
2267  }
2268  }
2269  }
2270  players_iterate(pplayer) { pplayer->tile_known->fill(false); }
2272 
2273  /* HACK: we read the known data from hex into 32-bit integers, and
2274  * now we convert it to the known tile data of each player. */
2275  whole_map_iterate(&(wld.map), ptile)
2276  {
2277  players_iterate(pplayer)
2278  {
2279  p = player_index(pplayer);
2280  l = player_index(pplayer) / 32;
2281 
2282  if (known[l * MAP_INDEX_SIZE + tile_index(ptile)]
2283  & (1u << (p % 32))) {
2284  map_set_known(ptile, pplayer);
2285  }
2286  }
2288  }
2290 
2291  delete[] known;
2292  known = nullptr;
2293  }
2294 }
2295 
2296 /* =======================================================================
2297  * Load player data.
2298  *
2299  * This is splitted into two parts as some data can only be loaded if the
2300  * number of players is known and the corresponding player slots are
2301  * defined.
2302  * ======================================================================= */
2303 
2307 static void sg_load_players_basic(struct loaddata *loading)
2308 {
2309  int i, k, nplayers;
2310  const char *string;
2311  bool shuffle_loaded = true;
2312 
2313  // Check status and return if not OK (sg_success != TRUE).
2314  sg_check_ret();
2315 
2316  if (S_S_INITIAL == loading->server_state || game.info.is_new_game) {
2317  // Nothing more to do.
2318  return;
2319  }
2320 
2321  // Load destroyed wonders:
2322  string = secfile_lookup_str(loading->file, "players.destroyed_wonders");
2323  sg_failure_ret(string != nullptr, "%s", secfile_error());
2324  sg_failure_ret(strlen(string) == loading->improvement.size,
2325  "Invalid length for 'players.destroyed_wonders' "
2326  "(%lu ~= %lu)",
2327  (unsigned long) qstrlen(string),
2328  (unsigned long) loading->improvement.size);
2329  for (k = 0; k < loading->improvement.size; k++) {
2330  sg_failure_ret(string[k] == '1' || string[k] == '0',
2331  "Undefined value '%c' within "
2332  "'players.destroyed_wonders'.",
2333  string[k]);
2334 
2335  if (string[k] == '1') {
2336  struct impr_type *pimprove =
2338  if (pimprove) {
2339  game.info.great_wonder_owners[improvement_index(pimprove)] =
2341  }
2342  }
2343  }
2344 
2345  server.identity_number = secfile_lookup_int_default(
2346  loading->file, server.identity_number, "players.identity_number_used");
2347 
2348  // First remove all defined players.
2349  players_iterate(pplayer) { server_remove_player(pplayer); }
2351 
2352  // Now, load the players from the savefile.
2353  player_slots_iterate(pslot)
2354  {
2355  struct player *pplayer;
2356  struct rgbcolor *prgbcolor = nullptr;
2357  int pslot_id = player_slot_index(pslot);
2358 
2359  if (nullptr
2360  == secfile_section_lookup(loading->file, "player%d", pslot_id)) {
2361  continue;
2362  }
2363 
2364  // Get player AI type.
2365  string = secfile_lookup_str(loading->file, "player%d.ai_type",
2366  player_slot_index(pslot));
2367  sg_failure_ret(string != nullptr, "%s", secfile_error());
2368 
2369  // Get player color
2370  if (!rgbcolor_load(loading->file, &prgbcolor, "player%d.color",
2371  pslot_id)) {
2372  if (loading->version >= 10 && game_was_started()) {
2373  /* 2.4.0 or later savegame. This is not an error in 2.3 savefiles,
2374  * as they predate the introduction of configurable player colors. */
2375  log_sg("Game has started, yet player %d has no color defined.",
2376  pslot_id);
2377  // This will be fixed up later
2378  } else {
2379  qDebug("No color defined for player %d.", pslot_id);
2380  /* Colors will be assigned on game start, or at end of savefile
2381  * loading if game has already started */
2382  }
2383  }
2384 
2385  // Create player.
2386  pplayer =
2387  server_create_player(player_slot_index(pslot), string, prgbcolor,
2388  game.scenario.allow_ai_type_fallback);
2389  sg_failure_ret(pplayer != nullptr, "Invalid AI type: '%s'!", string);
2390 
2391  server_player_init(pplayer, false, false);
2392 
2393  // Free the color definition.
2394  rgbcolor_destroy(prgbcolor);
2395 
2396  // Multipliers (policies)
2397 
2398  /* First initialise player values with ruleset defaults; this will
2399  * cover any in the ruleset not known when the savefile was created. */
2400  multipliers_iterate(pmul)
2401  {
2402  pplayer->multipliers[multiplier_index(pmul)] =
2403  pplayer->multipliers_target[multiplier_index(pmul)] = pmul->def;
2404  }
2406 
2407  // Now override with any values from the savefile.
2408  for (k = 0; k < loading->multiplier.size; k++) {
2409  const struct multiplier *pmul = loading->multiplier.order[k];
2410 
2411  if (pmul) {
2413  int val = secfile_lookup_int_default(loading->file, pmul->def,
2414  "player%d.multiplier%d.val",
2415  player_slot_index(pslot), k);
2416  int rval = (((CLIP(pmul->start, val, pmul->stop) - pmul->start)
2417  / pmul->step)
2418  * pmul->step)
2419  + pmul->start;
2420 
2421  if (rval != val) {
2422  qDebug("Player %d had illegal value for multiplier \"%s\": "
2423  "was %d, clamped to %d",
2424  pslot_id, multiplier_rule_name(pmul), val, rval);
2425  }
2426  pplayer->multipliers[idx] = rval;
2427 
2429  loading->file, pplayer->multipliers[idx],
2430  "player%d.multiplier%d.target", player_slot_index(pslot), k);
2431  rval = (((CLIP(pmul->start, val, pmul->stop) - pmul->start)
2432  / pmul->step)
2433  * pmul->step)
2434  + pmul->start;
2435 
2436  if (rval != val) {
2437  qDebug("Player %d had illegal value for multiplier_target "
2438  "\"%s\": was %d, clamped to %d",
2439  pslot_id, multiplier_rule_name(pmul), val, rval);
2440  }
2441  pplayer->multipliers_target[idx] = rval;
2442  } // else silently discard multiplier not in current ruleset
2443  }
2444 
2445  // Just in case savecompat starts adding it in the future.
2446  pplayer->server.border_vision = secfile_lookup_bool_default(
2447  loading->file, false, "player%d.border_vision",
2448  player_slot_index(pslot));
2449  }
2451 
2452  // check number of players
2453  nplayers =
2454  secfile_lookup_int_default(loading->file, 0, "players.nplayers");
2455  sg_failure_ret(player_count() == nplayers,
2456  "The value of players.nplayers "
2457  "(%d) from the loaded game does not match the number of "
2458  "players present (%d).",
2459  nplayers, player_count());
2460 
2461  // Load team informations.
2462  players_iterate(pplayer)
2463  {
2464  int team;
2465  struct team_slot *tslot = nullptr;
2466 
2468  "player%d.team_no",
2469  player_number(pplayer))
2470  && (tslot = team_slot_by_number(team)),
2471  "Invalid team definition for player %s (nb %d).",
2472  player_name(pplayer), player_number(pplayer));
2473  team_add_player(pplayer, team_new(tslot));
2474  }
2476 
2477  /* Loading the shuffle list is quite complex. At the time of saving the
2478  * shuffle data is saved as
2479  * shuffled_player_<number> = player_slot_id
2480  * where number is an increasing number and player_slot_id is a number
2481  * between 0 and the maximum number of player slots. Now we have to create
2482  * a list
2483  * shuffler_players[number] = player_slot_id
2484  * where all player slot IDs are used exactly one time. The code below
2485  * handles this ... */
2486  if (secfile_lookup_int_default(loading->file, -1,
2487  "players.shuffled_player_%d", 0)
2488  >= 0) {
2489  int shuffled_players[MAX_NUM_PLAYER_SLOTS];
2490  bool shuffled_player_set[MAX_NUM_PLAYER_SLOTS];
2491 
2492  player_slots_iterate(pslot)
2493  {
2494  int plrid = player_slot_index(pslot);
2495 
2496  // Array to save used numbers.
2497  shuffled_player_set[plrid] = false;
2498  /* List of all player IDs (needed for set_shuffled_players()). It is
2499  * initialised with the value -1 to indicate that no value is set. */
2500  shuffled_players[plrid] = -1;
2501  }
2503 
2504  // Load shuffled player list.
2505  for (i = 0; i < player_count(); i++) {
2506  int shuffle = secfile_lookup_int_default(
2507  loading->file, -1, "players.shuffled_player_%d", i);
2508 
2509  if (shuffle == -1) {
2510  log_sg("Missing player shuffle information (index %d) "
2511  "- reshuffle player list!",
2512  i);
2513  shuffle_loaded = false;
2514  break;
2515  } else if (shuffled_player_set[shuffle]) {
2516  log_sg("Player shuffle %d used two times "
2517  "- reshuffle player list!",
2518  shuffle);
2519  shuffle_loaded = false;
2520  break;
2521  }
2522  // Set this ID as used.
2523  shuffled_player_set[shuffle] = true;
2524 
2525  // Save the player ID in the shuffle list.
2526  shuffled_players[i] = shuffle;
2527  }
2528 
2529  if (shuffle_loaded) {
2530  // Insert missing numbers.
2531  int shuffle_index = player_count();
2532 
2533  for (i = 0; i < MAX_NUM_PLAYER_SLOTS; i++) {
2534  if (!shuffled_player_set[i]) {
2535  shuffled_players[shuffle_index] = i;
2536  shuffle_index++;
2537  }
2538  /* shuffle_index must not grow behind the size of shuffled_players.
2539  */
2540  sg_failure_ret(shuffle_index <= MAX_NUM_PLAYER_SLOTS,
2541  "Invalid player shuffle data!");
2542  }
2543 
2544 #ifdef FREECIV_DEBUG
2545  log_debug("[load shuffle] player_count() = %d", player_count());
2546  player_slots_iterate(pslot)
2547  {
2548  int plrid = player_slot_index(pslot);
2549  log_debug("[load shuffle] id: %3d => slot: %3d | slot %3d: %s",
2550  plrid, shuffled_players[plrid], plrid,
2551  shuffled_player_set[plrid] ? "is used" : "-");
2552  }
2554 #endif // FREECIV_DEBUG
2555 
2556  // Set shuffle list from savegame.
2557  set_shuffled_players(shuffled_players);
2558  }
2559  }
2560 
2561  if (!shuffle_loaded) {
2562  /* No shuffled players included or error loading them, so shuffle them
2563  * (this may include scenarios). */
2564  shuffle_players();
2565  }
2566 }
2567 
2571 static void sg_load_players(struct loaddata *loading)
2572 {
2573  // Check status and return if not OK (sg_success != TRUE).
2574  sg_check_ret();
2575 
2576  if (game.info.is_new_game) {
2577  // Nothing to do.
2578  return;
2579  }
2580 
2581  players_iterate(pplayer)
2582  {
2583  sg_load_player_main(loading, pplayer);
2584  sg_load_player_cities(loading, pplayer);
2585  sg_load_player_units(loading, pplayer);
2586  sg_load_player_attributes(loading, pplayer);
2587 
2588  // Check the success of the functions above.
2589  sg_check_ret();
2590 
2591  // print out some informations
2592  if (is_ai(pplayer)) {
2593  qInfo(_("%s has been added as %s level AI-controlled player "
2594  "(%s)."),
2595  player_name(pplayer),
2596  ai_level_translated_name(pplayer->ai_common.skill_level),
2597  ai_name(pplayer->ai));
2598  } else {
2599  qInfo(_("%s has been added as human player."), player_name(pplayer));
2600  }
2601  }
2603 
2604  /* Also load the transport status of the units here. It must be a special
2605  * case as all units must be known (unit on an allied transporter). */
2606  players_iterate(pplayer)
2607  {
2608  // Load unit transport status.
2609  sg_load_player_units_transport(loading, pplayer);
2610  }
2612 
2613  /* Savegame may contain nation assignments that are incompatible with the
2614  * current nationset -- for instance, if it predates the introduction of
2615  * nationsets. Ensure they are compatible, one way or another. */
2617 
2618  /* Some players may have invalid nations in the ruleset. Once all players
2619  * are loaded, pick one of the remaining nations for them. */
2620  players_iterate(pplayer)
2621  {
2622  if (pplayer->nation == NO_NATION_SELECTED) {
2624  pplayer, pick_a_nation(nullptr, false, true, NOT_A_BARBARIAN));
2625  // TRANS: Minor error message: <Leader> ... <Poles>.
2626  log_sg(_("%s had invalid nation; changing to %s."),
2627  player_name(pplayer), nation_plural_for_player(pplayer));
2628 
2629  ai_traits_init(pplayer);
2630  }
2631  }
2633 
2634  // Sanity check alliances, prevent allied-with-ally-of-enemy.
2636  {
2637  players_iterate_alive(aplayer)
2638  {
2639  if (pplayers_allied(plr, aplayer)) {
2640  enum dipl_reason can_ally =
2641  pplayer_can_make_treaty(plr, aplayer, DS_ALLIANCE);
2642  if (can_ally == DIPL_ALLIANCE_PROBLEM_US
2643  || can_ally == DIPL_ALLIANCE_PROBLEM_THEM) {
2644  log_sg("Illegal alliance structure detected: "
2645  "%s alliance to %s reduced to peace treaty.",
2648  player_diplstate_get(plr, aplayer)->type = DS_PEACE;
2649  player_diplstate_get(aplayer, plr)->type = DS_PEACE;
2650  }
2651  }
2652  }
2654  }
2656 
2657  /* Update cached city illness. This can depend on trade routes,
2658  * so can't be calculated until all players have been loaded. */
2659  if (game.info.illness_on) {
2660  cities_iterate(pcity)
2661  {
2662  pcity->server.illness = city_illness_calc(
2663  pcity, nullptr, nullptr, &(pcity->illness_trade), nullptr);
2664  }
2666  }
2667 
2668  /* Update all city information. This must come after all cities are
2669  * loaded (in player_load) but before player (dumb) cities are loaded
2670  * in player_load_vision(). */
2671  players_iterate(plr)
2672  {
2673  city_list_iterate(plr->cities, pcity)
2674  {
2675  city_refresh(pcity);
2676  sanity_check_city(pcity);
2677  CALL_PLR_AI_FUNC(city_got, plr, plr, pcity);
2678  }
2680  }
2682 
2683  /* Since the cities must be placed on the map to put them on the
2684  player map we do this afterwards */
2685  players_iterate(pplayer)
2686  {
2687  sg_load_player_vision(loading, pplayer);
2688  // Check the success of the function above.
2689  sg_check_ret();
2690  }
2692 
2693  // Check shared vision.
2694  players_iterate(pplayer)
2695  {
2696  BV_CLR_ALL(pplayer->gives_shared_vision);
2697  BV_CLR_ALL(pplayer->server.really_gives_vision);
2698  }
2700 
2701  players_iterate(pplayer)
2702  {
2703  int plr1 = player_index(pplayer);
2704 
2705  players_iterate(pplayer2)
2706  {
2707  int plr2 = player_index(pplayer2);
2709  loading->file, false,
2710  "player%d.diplstate%d.gives_shared_vision", plr1, plr2)) {
2711  give_shared_vision(pplayer, pplayer2);
2712  }
2713  }
2715  }
2717 
2720 
2721  // All vision is ready; this calls city_thaw_workers_queue().
2723 
2724  // Make sure everything is consistent.
2725  players_iterate(pplayer)
2726  {
2727  unit_list_iterate(pplayer->units, punit)
2728  {
2729  if (!can_unit_continue_current_activity(punit)) {
2730  log_sg("Unit doing illegal activity in savegame!");
2731  log_sg(
2732  "Activity: %s, Target: %s", unit_activity_name(punit->activity),
2733  punit->activity_target ? extra_rule_name(punit->activity_target)
2734  : "missing");
2735  punit->activity = ACTIVITY_IDLE;
2736  }
2737  }
2739  }
2741 
2742  cities_iterate(pcity)
2743  {
2744  city_refresh(pcity);
2745  city_thaw_workers(pcity); // may auto_arrange_workers()
2746  }
2748 
2749  /* Player colors are always needed once game has started. Pre-2.4 savegames
2750  * lack them. This cannot be in compatibility conversion layer as we need
2751  * all the player data available to be able to assign best colors. */
2752  if (game_was_started()) {
2754  }
2755 }
2756 
2760 static void sg_load_player_main(struct loaddata *loading, struct player *plr)
2761 {
2762  const char **slist;
2763  int i, plrno = player_number(plr);
2764  const char *string;
2765  struct government *gov;
2766  const char *level;
2767  const char *barb_str;
2768  size_t nval;
2769 
2770  // Check status and return if not OK (sg_success != TRUE).
2771  sg_check_ret();
2772 
2773  // Basic player data.
2774  string = secfile_lookup_str(loading->file, "player%d.name", plrno);
2775  sg_failure_ret(string != nullptr, "%s", secfile_error());
2776  server_player_set_name(plr, string);
2777  sz_strlcpy(plr->username,
2778  secfile_lookup_str_default(loading->file, "",
2779  "player%d.username", plrno));
2781  "player%d.unassigned_user", plrno),
2782  "%s", secfile_error());
2783  sz_strlcpy(plr->server.orig_username,
2784  secfile_lookup_str_default(loading->file, "",
2785  "player%d.orig_username", plrno));
2787  secfile_lookup_str_default(loading->file, "",
2788  "player%d.ranked_username", plrno));
2790  "player%d.unassigned_ranked", plrno),
2791  "%s", secfile_error());
2792  string = secfile_lookup_str_default(loading->file, "",
2793  "player%d.delegation_username", plrno);
2794  // Defaults to no delegation.
2795  if (strlen(string)) {
2796  player_delegation_set(plr, string);
2797  }
2798 
2799  // Player flags
2800  BV_CLR_ALL(plr->flags);
2801  slist =
2802  secfile_lookup_str_vec(loading->file, &nval, "player%d.flags", plrno);
2803  for (i = 0; i < nval; i++) {
2804  const char *sval = slist[i];
2805  enum plr_flag_id fid = plr_flag_id_by_name(sval, fc_strcasecmp);
2806 
2807  BV_SET(plr->flags, fid);
2808  }
2809  delete[] slist;
2810 
2811  // Nation
2812  string = secfile_lookup_str(loading->file, "player%d.nation", plrno);
2813  player_set_nation(plr, nation_by_rule_name(string));
2814  if (plr->nation != nullptr) {
2815  ai_traits_init(plr);
2816  }
2817 
2818  // Government
2819  string =
2820  secfile_lookup_str(loading->file, "player%d.government_name", plrno);
2821  gov = government_by_rule_name(string);
2822  sg_failure_ret(gov != nullptr, "Player%d: unsupported government \"%s\".",
2823  plrno, string);
2824  plr->government = gov;
2825 
2826  // Target government
2827  string = secfile_lookup_str(loading->file,
2828  "player%d.target_government_name", plrno);
2829  if (string) {
2831  } else {
2832  plr->target_government = nullptr;
2833  }
2835  loading->file, -1, "player%d.revolution_finishes", plrno);
2836 
2838  &plr->server.got_first_city,
2839  "player%d.got_first_city", plrno),
2840  "%s", secfile_error());
2841 
2842  /* Load diplomatic data (diplstate + embassy + vision).
2843  * Shared vision is loaded in sg_load_players(). */
2844  BV_CLR_ALL(plr->real_embassy);
2845  players_iterate(pplayer)
2846  {
2847  char buf[32];
2848  int unconverted;
2849  struct player_diplstate *ds = player_diplstate_get(plr, pplayer);
2850  i = player_index(pplayer);
2851 
2852  // load diplomatic status
2853  fc_snprintf(buf, sizeof(buf), "player%d.diplstate%d", plrno, i);
2854 
2855  unconverted =
2856  secfile_lookup_int_default(loading->file, -1, "%s.type", buf);
2857  if (unconverted >= 0 && unconverted < loading->ds_t.size) {
2858  // Look up what state the unconverted number represents.
2859  ds->type = loading->ds_t.order[unconverted];
2860  } else {
2861  log_sg("No valid diplomatic state type between players %d and %d",
2862  plrno, i);
2863 
2864  ds->type = DS_WAR;
2865  }
2866 
2867  unconverted =
2868  secfile_lookup_int_default(loading->file, -1, "%s.max_state", buf);
2869  if (unconverted >= 0 && unconverted < loading->ds_t.size) {
2870  // Look up what state the unconverted number represents.
2871  ds->max_state = loading->ds_t.order[unconverted];
2872  } else {
2873  log_sg("No valid diplomatic max_state between players %d and %d",
2874  plrno, i);
2875 
2876  ds->max_state = DS_WAR;
2877  }
2878 
2880  loading->file, 0, "%s.first_contact_turn", buf);
2881  ds->turns_left =
2882  secfile_lookup_int_default(loading->file, -2, "%s.turns_left", buf);
2884  loading->file, 0, "%s.has_reason_to_cancel", buf);
2886  loading->file, 0, "%s.contact_turns_left", buf);
2887 
2888  if (secfile_lookup_bool_default(loading->file, false, "%s.embassy",
2889  buf)) {
2890  BV_SET(plr->real_embassy, i);
2891  }
2892  /* 'gives_shared_vision' is loaded in sg_load_players() as all cities
2893  * must be known. */
2894  }
2896 
2897  // load ai data
2898  players_iterate(aplayer)
2899  {
2900  char buf[32];
2901 
2902  fc_snprintf(buf, sizeof(buf), "player%d.ai%d", plrno,
2903  player_index(aplayer));
2904 
2905  plr->ai_common.love[player_index(aplayer)] =
2906  secfile_lookup_int_default(loading->file, 1, "%s.love", buf);
2907  CALL_FUNC_EACH_AI(player_load_relations, plr, aplayer, loading->file,
2908  plrno);
2909  }
2911 
2912  CALL_FUNC_EACH_AI(player_load, plr, loading->file, plrno);
2913 
2914  // Some sane defaults
2915  plr->ai_common.fuzzy = 0;
2916  plr->ai_common.expand = 100;
2917  plr->ai_common.science_cost = 100;
2918 
2919  level = secfile_lookup_str_default(loading->file, nullptr,
2920  "player%d.ai.level", plrno);
2921  if (level != nullptr) {
2922  plr->ai_common.skill_level = ai_level_by_name(level, fc_strcasecmp);
2923 
2924  /* In builds where level "Experimental" is not supported, convert it to
2925  * "Hard" */
2926  if (!ai_level_is_valid(plr->ai_common.skill_level)
2927  && !fc_strcasecmp(level, "Experimental")) {
2928  plr->ai_common.skill_level = AI_LEVEL_HARD;
2929  }
2930  } else {
2931  plr->ai_common.skill_level = ai_level_invalid();
2932  }
2933 
2934  if (!ai_level_is_valid(plr->ai_common.skill_level)) {
2936  secfile_lookup_int_default(loading->file, game.info.skill_level,
2937  "player%d.ai.skill_level", plrno));
2938  }
2939 
2940  barb_str = secfile_lookup_str_default(loading->file, "None",
2941  "player%d.ai.barb_type", plrno);
2942  plr->ai_common.barbarian_type =
2943  barbarian_type_by_name(barb_str, fc_strcasecmp);
2944 
2945  if (!barbarian_type_is_valid(plr->ai_common.barbarian_type)) {
2946  log_sg("Player%d: Invalid barbarian type \"%s\". "
2947  "Changed to \"None\".",
2948  plrno, barb_str);
2949  plr->ai_common.barbarian_type = NOT_A_BARBARIAN;
2950  }
2951 
2952  if (is_barbarian(plr)) {
2953  server.nbarbarians++;
2954  }
2955 
2956  if (is_ai(plr)) {
2958  CALL_PLR_AI_FUNC(gained_control, plr, plr);
2959  }
2960 
2961  // Load nation style.
2962  {
2963  struct nation_style *style;
2964 
2965  string =
2966  secfile_lookup_str(loading->file, "player%d.style_by_name", plrno);
2967 
2968  // Handle pre-2.6 savegames
2969  if (string == nullptr) {
2970  string = secfile_lookup_str(loading->file,
2971  "player%d.city_style_by_name", plrno);
2972  }
2973 
2974  sg_failure_ret(string != nullptr, "%s", secfile_error());
2975  style = style_by_rule_name(string);
2976  if (style == nullptr) {
2977  style = style_by_number(0);
2978  log_sg("Player%d: unsupported city_style_name \"%s\". "
2979  "Changed to \"%s\".",
2980  plrno, string, style_rule_name(style));
2981  }
2982  plr->style = style;
2983  }
2984 
2986  "player%d.idle_turns", plrno),
2987  "%s", secfile_error());
2988  plr->is_male = secfile_lookup_bool_default(loading->file, true,
2989  "player%d.is_male", plrno);
2991  "player%d.is_alive", plrno),
2992  "%s", secfile_error());
2994  "player%d.turns_alive", plrno),
2995  "%s", secfile_error());
2997  "player%d.last_war", plrno),
2998  "%s", secfile_error());
3000  loading->file, false, "player%d.phase_done", plrno);
3002  "player%d.gold", plrno),
3003  "%s", secfile_error());
3005  "player%d.rates.tax", plrno),
3006  "%s", secfile_error());
3008  "player%d.rates.science", plrno),
3009  "%s", secfile_error());
3011  "player%d.rates.luxury", plrno),
3012  "%s", secfile_error());
3013  plr->server.bulbs_last_turn = secfile_lookup_int_default(
3014  loading->file, 0, "player%d.research.bulbs_last_turn", plrno);
3015 
3016  // Traits
3017  if (plr->nation) {
3018  for (i = 0; i < loading->trait.size; i++) {
3019  enum trait tr = trait_by_name(loading->trait.order[i], fc_strcasecmp);
3020 
3021  if (trait_is_valid(tr)) {
3022  int val = secfile_lookup_int_default(
3023  loading->file, -1, "player%d.trait%d.val", plrno, i);
3024 
3025  if (val != -1) {
3026  plr->ai_common.traits[tr].val = val;
3027  }
3028 
3029  sg_failure_ret(secfile_lookup_int(loading->file, &val,
3030  "player%d.trait%d.mod", plrno, i),
3031  "%s", secfile_error());
3032  plr->ai_common.traits[tr].mod = val;
3033  }
3034  }
3035  }
3036 
3037  // Achievements
3038  {
3039  int count;
3040 
3041  count = secfile_lookup_int_default(loading->file, -1,
3042  "player%d.achievement_count", plrno);
3043 
3044  if (count > 0) {
3045  for (i = 0; i < count; i++) {
3046  const char *name;
3047  struct achievement *pach;
3048  bool first;
3049 
3050  name = secfile_lookup_str(loading->file,
3051  "player%d.achievement%d.name", plrno, i);
3053 
3054  sg_failure_ret(pach != nullptr, "Unknown achievement \"%s\".", name);
3055 
3057  "player%d.achievement%d.first",
3058  plrno, i),
3059  "achievement error: %s", secfile_error());
3060 
3062  pach->first == nullptr || !first,
3063  "Multiple players listed as first to get achievement \"%s\".",
3064  name);
3065 
3066  BV_SET(pach->achievers, player_index(plr));
3067 
3068  if (first) {
3069  pach->first = plr;
3070  }
3071  }
3072  }
3073  }
3074 
3075  // Player score.
3076  plr->score.happy =
3077  secfile_lookup_int_default(loading->file, 0, "score%d.happy", plrno);
3078  plr->score.content =
3079  secfile_lookup_int_default(loading->file, 0, "score%d.content", plrno);
3080  plr->score.unhappy =
3081  secfile_lookup_int_default(loading->file, 0, "score%d.unhappy", plrno);
3082  plr->score.angry =
3083  secfile_lookup_int_default(loading->file, 0, "score%d.angry", plrno);
3084 
3085  /* Make sure that the score about specialists in current ruleset that
3086  * were not present at saving time are set to zero. */
3087  specialist_type_iterate(sp) { plr->score.specialists[sp] = 0; }
3089 
3090  for (i = 0; i < loading->specialist.size; i++) {
3091  plr->score.specialists[specialist_index(loading->specialist.order[i])] =
3092  secfile_lookup_int_default(loading->file, 0, "score%d.specialists%d",
3093  plrno, i);
3094  }
3095 
3096  plr->score.wonders =
3097  secfile_lookup_int_default(loading->file, 0, "score%d.wonders", plrno);
3098  plr->score.techs =
3099  secfile_lookup_int_default(loading->file, 0, "score%d.techs", plrno);
3100  plr->score.techout =
3101  secfile_lookup_int_default(loading->file, 0, "score%d.techout", plrno);
3103  loading->file, 0, "score%d.landarea", plrno);
3105  loading->file, 0, "score%d.settledarea", plrno);
3107  loading->file, 0, "score%d.population", plrno);
3108  plr->score.cities =
3109  secfile_lookup_int_default(loading->file, 0, "score%d.cities", plrno);
3110  plr->score.units =
3111  secfile_lookup_int_default(loading->file, 0, "score%d.units", plrno);
3113  loading->file, 0, "score%d.pollution", plrno);
3115  loading->file, 0, "score%d.literacy", plrno);
3116  plr->score.bnp =
3117  secfile_lookup_int_default(loading->file, 0, "score%d.bnp", plrno);
3118  plr->score.mfg =
3119  secfile_lookup_int_default(loading->file, 0, "score%d.mfg", plrno);
3121  loading->file, 0, "score%d.spaceship", plrno);
3123  loading->file, 0, "score%d.units_built", plrno);
3125  loading->file, 0, "score%d.units_killed", plrno);
3127  loading->file, 0, "score%d.units_lost", plrno);
3128  plr->score.culture =
3129  secfile_lookup_int_default(loading->file, 0, "score%d.culture", plrno);
3130  plr->score.game =
3131  secfile_lookup_int_default(loading->file, 0, "score%d.total", plrno);
3132 
3133  // Load space ship data.
3134  {
3135  struct player_spaceship *ship = &plr->spaceship;
3136  char prefix[32];
3137  const char *st;
3138  int ei;
3139 
3140  fc_snprintf(prefix, sizeof(prefix), "player%d.spaceship", plrno);
3141  spaceship_init(ship);
3143  secfile_lookup_int(loading->file, &ei, "%s.state", prefix), "%s",
3144  secfile_error());
3145  ship->state = static_cast<spaceship_state>(ei);
3146 
3147  if (ship->state != SSHIP_NONE) {
3149  "%s.structurals", prefix),
3150  "%s", secfile_error());
3152  "%s.components", prefix),
3153  "%s", secfile_error());
3154  sg_failure_ret(secfile_lookup_int(loading->file, &ship->modules,
3155  "%s.modules", prefix),
3156  "%s", secfile_error());
3158  secfile_lookup_int(loading->file, &ship->fuel, "%s.fuel", prefix),
3159  "%s", secfile_error());
3161  "%s.propulsion", prefix),
3162  "%s", secfile_error());
3164  "%s.habitation", prefix),
3165  "%s", secfile_error());
3167  "%s.life_support", prefix),
3168  "%s", secfile_error());
3170  "%s.solar_panels", prefix),
3171  "%s", secfile_error());
3172 
3173  st = secfile_lookup_str(loading->file, "%s.structure", prefix);
3175  st != nullptr, "%s",
3176  secfile_error()) for (i = 0; i < NUM_SS_STRUCTURALS && st[i]; i++)
3177  {
3178  sg_failure_ret(st[i] == '1' || st[i] == '0',
3179  "Undefined value '%c' within '%s.structure'.", st[i],
3180  prefix)
3181 
3182  if (st[i] != '0')
3183  {
3184  BV_SET(ship->structure, i);
3185  }
3186  }
3187  if (ship->state >= SSHIP_LAUNCHED) {
3189  "%s.launch_year", prefix),
3190  "%s", secfile_error());
3191  }
3192  spaceship_calc_derived(ship);
3193  }
3194  }
3195 
3196  // Load lost wonder data.
3197  string = secfile_lookup_str(loading->file, "player%d.lost_wonders", plrno);
3198  // If not present, probably an old savegame; nothing to be done
3199  if (string) {
3200  int k;
3201  sg_failure_ret(strlen(string) == loading->improvement.size,
3202  "Invalid length for 'player%d.lost_wonders' "
3203  "(%lu ~= %lu)",
3204  plrno, (unsigned long) qstrlen(string),
3205  (unsigned long) loading->improvement.size);
3206  for (k = 0; k < loading->improvement.size; k++) {
3207  sg_failure_ret(string[k] == '1' || string[k] == '0',
3208  "Undefined value '%c' within "
3209  "'player%d.lost_wonders'.",
3210  plrno, string[k]);
3211 
3212  if (string[k] == '1') {
3213  struct impr_type *pimprove =
3215  if (pimprove) {
3216  plr->wonders[improvement_index(pimprove)] = WONDER_LOST;
3217  }
3218  }
3219  }
3220  }
3221 
3222  plr->history = secfile_lookup_int_default(loading->file, 0,
3223  "player%d.culture", plrno);
3224  plr->server.huts = secfile_lookup_int_default(loading->file, 0,
3225  "player%d.hut_count", plrno);
3226 }
3227 
3231 static void sg_load_player_cities(struct loaddata *loading,
3232  struct player *plr)
3233 {
3234  int ncities, i, plrno = player_number(plr);
3235  bool tasks_handled;
3236 
3237  // Check status and return if not OK (sg_success != TRUE).
3238  sg_check_ret();
3239 
3241  secfile_lookup_int(loading->file, &ncities, "player%d.ncities", plrno),
3242  "%s", secfile_error());
3243 
3244  if (!plr->is_alive && ncities > 0) {
3245  log_sg("'player%d.ncities' = %d for dead player!", plrno, ncities);
3246  ncities = 0;
3247  }
3248 
3249  if (!plr->server.got_first_city && ncities > 0) {
3250  // Probably barbarians in an old savegame; fix up
3251  plr->server.got_first_city = true;
3252  }
3253 
3254  // Load all cities of the player.
3255  for (i = 0; i < ncities; i++) {
3256  char buf[32];
3257  struct city *pcity;
3258 
3259  fc_snprintf(buf, sizeof(buf), "player%d.c%d", plrno, i);
3260 
3261  // Create a dummy city.
3262  pcity = create_city_virtual(plr, nullptr, buf);
3263  adv_city_alloc(pcity);
3264  if (!sg_load_player_city(loading, plr, pcity, buf)) {
3265  adv_city_free(pcity);
3266  destroy_city_virtual(pcity);
3267  sg_failure_ret(false, "Error loading city %d of player %d.", i, plrno);
3268  }
3269 
3270  identity_number_reserve(pcity->id);
3271  idex_register_city(&wld, pcity);
3272 
3273  /* Load the information about the nationality of citizens. This is done
3274  * here because the city sanity check called by citizens_update()
3275  * requires that the city is registered. */
3276  sg_load_player_city_citizens(loading, plr, pcity, buf);
3277 
3278  // After everything is loaded, but before vision.
3279  map_claim_ownership(city_tile(pcity), plr, city_tile(pcity), true);
3280 
3281  // adding the city contribution to fog-of-war
3282  pcity->server.vision = vision_new(plr, city_tile(pcity));
3283  vision_reveal_tiles(pcity->server.vision,
3284  game.server.vision_reveal_tiles);
3285  city_refresh_vision(pcity);
3286 
3287  city_list_append(plr->cities, pcity);
3288  }
3289 
3290  tasks_handled = false;
3291  for (i = 0; !tasks_handled; i++) {
3292  int city_id;
3293  struct city *pcity = nullptr;
3294 
3295  city_id = secfile_lookup_int_default(loading->file, -1,
3296  "player%d.task%d.city", plrno, i);
3297 
3298  if (city_id != -1) {
3299  pcity = player_city_by_number(plr, city_id);
3300  }
3301 
3302  if (pcity != nullptr) {
3303  const char *str;
3304  int nat_x, nat_y;
3305  struct worker_task *ptask = new worker_task();
3306 
3307  nat_x = secfile_lookup_int_default(loading->file, -1,
3308  "player%d.task%d.x", plrno, i);
3309  nat_y = secfile_lookup_int_default(loading->file, -1,
3310  "player%d.task%d.y", plrno, i);
3311 
3312  ptask->ptile = native_pos_to_tile(&(wld.map), nat_x, nat_y);
3313 
3314  str = secfile_lookup_str(loading->file, "player%d.task%d.activity",
3315  plrno, i);
3316  ptask->act = unit_activity_by_name(str, fc_strcasecmp);
3317 
3318  sg_failure_ret(unit_activity_is_valid(ptask->act),
3319  "Unknown workertask activity %s", str);
3320 
3321  str = secfile_lookup_str(loading->file, "player%d.task%d.target",
3322  plrno, i);
3323 
3324  if (strcmp("-", str)) {
3325  ptask->tgt = extra_type_by_rule_name(str);
3326 
3327  sg_failure_ret(ptask->tgt != nullptr, "Unknown workertask target %s",
3328  str);
3329  } else {
3330  ptask->tgt = nullptr;
3331  }
3332 
3334  loading->file, 1, "player%d.task%d.want", plrno, i);
3335 
3336  worker_task_list_append(pcity->task_reqs, ptask);
3337  } else {
3338  tasks_handled = true;
3339  }
3340  }
3341 }
3342 
3346 static bool sg_load_player_city(struct loaddata *loading, struct player *plr,
3347  struct city *pcity, const char *citystr)
3348 {
3349  struct player *past;
3350  const char *kind, *name, *string;
3351  int id, i, repair, sp_count = 0, workers = 0, value;
3352  int nat_x, nat_y;
3353  citizens size;
3354  const char *stylename;
3355 
3356  sg_warn_ret_val(secfile_lookup_int(loading->file, &nat_x, "%s.x", citystr),
3357  false, "%s", secfile_error());
3358  sg_warn_ret_val(secfile_lookup_int(loading->file, &nat_y, "%s.y", citystr),
3359  false, "%s", secfile_error());
3360  pcity->tile = native_pos_to_tile(&(wld.map), nat_x, nat_y);
3361  sg_warn_ret_val(nullptr != pcity->tile, false,
3362  "%s has invalid center tile (%d, %d)", citystr, nat_x,
3363  nat_y);
3364  sg_warn_ret_val(nullptr == tile_city(pcity->tile), false,
3365  "%s duplicates city (%d, %d)", citystr, nat_x, nat_y);
3366 
3367  // Instead of dying, use 'citystr' string for damaged name.
3368  sz_strlcpy(pcity->name, secfile_lookup_str_default(loading->file, citystr,
3369  "%s.name", citystr));
3370 
3372  secfile_lookup_int(loading->file, &pcity->id, "%s.id", citystr), false,
3373  "%s", secfile_error());
3374 
3375  id = secfile_lookup_int_default(loading->file, player_number(plr),
3376  "%s.original", citystr);
3377  past = player_by_number(id);
3378  if (nullptr != past) {
3379  pcity->original = past;
3380  }
3381 
3383  secfile_lookup_int(loading->file, &value, "%s.size", citystr), false,
3384  "%s", secfile_error());
3385  size = static_cast<citizens>(value); // set the correct type
3386  sg_warn_ret_val(value == (int) size, false,
3387  "Invalid city size: %d, set to %d", value, size);
3388  city_size_set(pcity, size);
3389 
3390  for (i = 0; i < loading->specialist.size; i++) {
3392  secfile_lookup_int(loading->file, &value, "%s.nspe%d", citystr, i),
3393  false, "%s", secfile_error());
3394  pcity->specialists[specialist_index(loading->specialist.order[i])] =
3395  static_cast<citizens>(value);
3396  sp_count += value;
3397  }
3398 
3399  for (i = 0; i < MAX_TRADE_ROUTES; i++) {
3400  int partner = secfile_lookup_int_default(loading->file, 0,
3401  "%s.traderoute%d", citystr, i);
3402 
3403  if (partner != 0) {
3404  struct trade_route *proute = new trade_route();
3405 
3406  proute->partner = partner;
3407  proute->dir = RDIR_BIDIRECTIONAL;
3408  proute->goods = goods_by_number(0); // First good
3409 
3410  trade_route_list_append(pcity->routes, proute);
3411  }
3412  }
3413 
3415  "%s.food_stock", citystr),
3416  false, "%s", secfile_error());
3418  "%s.shield_stock", citystr),
3419  false, "%s", secfile_error());
3420  pcity->history =
3421  secfile_lookup_int_default(loading->file, 0, "%s.history", citystr);
3422 
3423  pcity->airlift =
3424  secfile_lookup_int_default(loading->file, 0, "%s.airlift", citystr);
3425  pcity->was_happy = secfile_lookup_bool_default(loading->file, false,
3426  "%s.was_happy", citystr);
3427 
3428  pcity->turn_plague = secfile_lookup_int_default(loading->file, 0,
3429  "%s.turn_plague", citystr);
3430 
3431  sg_warn_ret_val(secfile_lookup_int(loading->file, &pcity->anarchy,
3432  "%s.anarchy", citystr),
3433  false, "%s", secfile_error());
3434  pcity->rapture =
3435  secfile_lookup_int_default(loading->file, 0, "%s.rapture", citystr);
3436  pcity->steal =
3437  secfile_lookup_int_default(loading->file, 0, "%s.steal", citystr);
3438 
3439  // before did_buy for undocumented hack
3441  loading->file, -2, "%s.turn_founded", citystr);
3443  secfile_lookup_int(loading->file, &i, "%s.did_buy", citystr), false,
3444  "%s", secfile_error());
3445  pcity->did_buy = (i != 0);
3446  if (i == -1 && pcity->turn_founded == -2) {
3447  // undocumented hack
3448  pcity->turn_founded = game.info.turn;
3449  }
3450 
3451  pcity->did_sell = secfile_lookup_bool_default(loading->file, false,
3452  "%s.did_sell", citystr);
3453 
3455  "%s.turn_last_built", citystr),
3456  false, "%s", secfile_error());
3457 
3458  kind = secfile_lookup_str(loading->file, "%s.currently_building_kind",
3459  citystr);
3460  name = secfile_lookup_str(loading->file, "%s.currently_building_name",
3461  citystr);
3462  pcity->production = universal_by_rule_name(kind, name);
3463  sg_warn_ret_val(pcity->production.kind != universals_n_invalid(), false,
3464  "%s.currently_building: unknown \"%s\" \"%s\".", citystr,
3465  kind, name);
3466 
3467  kind = secfile_lookup_str(loading->file, "%s.changed_from_kind", citystr);
3468  name = secfile_lookup_str(loading->file, "%s.changed_from_name", citystr);
3469  pcity->changed_from = universal_by_rule_name(kind, name);
3470  sg_warn_ret_val(pcity->changed_from.kind != universals_n_invalid(), false,
3471  "%s.changed_from: unknown \"%s\" \"%s\".", citystr, kind,
3472  name);
3473 
3474  pcity->before_change_shields =
3475  secfile_lookup_int_default(loading->file, pcity->shield_stock,
3476  "%s.before_change_shields", citystr);
3478  loading->file, 0, "%s.caravan_shields", citystr);
3480  loading->file, 0, "%s.disbanded_shields", citystr);
3482  loading->file, 0, "%s.last_turns_shield_surplus", citystr);
3483 
3484  stylename = secfile_lookup_str_default(loading->file, nullptr, "%s.style",
3485  citystr);
3486  if (stylename != nullptr) {
3487  pcity->style = city_style_by_rule_name(stylename);
3488  } else {
3489  pcity->style = 0;
3490  }
3491  if (pcity->style < 0) {
3492  pcity->style = city_style(pcity);
3493  }
3494 
3495  pcity->server.synced = false; // must re-sync with clients
3496 
3497  // Initialise list of city improvements.
3498  for (i = 0; i < ARRAY_SIZE(pcity->built); i++) {
3499  pcity->built[i].turn = I_NEVER;
3500  }
3501 
3502  // Load city improvements.
3503  string = secfile_lookup_str(loading->file, "%s.improvements", citystr);
3504  sg_warn_ret_val(string != nullptr, false, "%s", secfile_error());
3505  sg_warn_ret_val(strlen(string) == loading->improvement.size, false,
3506  "Invalid length of '%s.improvements' (%lu ~= %lu).",
3507  citystr, (unsigned long) qstrlen(string),
3508  (unsigned long) loading->improvement.size);
3509  for (i = 0; i < loading->improvement.size; i++) {
3510  sg_warn_ret_val(string[i] == '1' || string[i] == '0', false,
3511  "Undefined value '%c' within '%s.improvements'.",
3512  string[i], citystr)
3513 
3514  if (string[i] == '1')
3515  {
3516  struct impr_type *pimprove =
3518  if (pimprove) {
3519  city_add_improvement(pcity, pimprove);
3520  }
3521  }
3522  }
3523 
3524  sg_failure_ret_val(loading->worked_tiles != nullptr, false,
3525  "No worked tiles map defined.");
3526 
3527  city_freeze_workers(pcity);
3528 
3529  /* load new savegame with variable (squared) city radius and worked
3530  * tiles map */
3531 
3532  int radius_sq = secfile_lookup_int_default(loading->file, -1,
3533  "%s.city_radius_sq", citystr);
3534  city_map_radius_sq_set(pcity, radius_sq);
3535 
3536  city_tile_iterate(radius_sq, city_tile(pcity), ptile)
3537  {
3538  if (loading->worked_tiles[ptile->index] == pcity->id) {
3539  tile_set_worked(ptile, pcity);
3540  workers++;
3541 
3542 #ifdef FREECIV_DEBUG
3543  /* set this tile to unused; a check for not resetted tiles is
3544  * included in game_load_internal() */
3545  loading->worked_tiles[ptile->index] = -1;
3546 #endif // FREECIV_DEBUG
3547  }
3548  }
3550 
3551  if (tile_worked(city_tile(pcity)) != pcity) {
3552  struct city *pwork = tile_worked(city_tile(pcity));
3553 
3554  if (nullptr != pwork) {
3555  log_sg("[%s] city center of '%s' (%d,%d) [%d] is worked by '%s' "
3556  "(%d,%d) [%d]; repairing ",
3557  citystr, city_name_get(pcity), TILE_XY(city_tile(pcity)),
3558  city_size_get(pcity), city_name_get(pwork),
3559  TILE_XY(city_tile(pwork)), city_size_get(pwork));
3560 
3561  tile_set_worked(city_tile(pcity), nullptr); // remove tile from pwork
3562  pwork->specialists[DEFAULT_SPECIALIST]++;
3563  auto_arrange_workers(pwork);
3564  } else {
3565  log_sg("[%s] city center of '%s' (%d,%d) [%d] is empty; repairing ",
3566  citystr, city_name_get(pcity), TILE_XY(city_tile(pcity)),
3567  city_size_get(pcity));
3568  }
3569 
3570  // repair pcity
3571  tile_set_worked(city_tile(pcity), pcity);
3572  city_repair_size(pcity, -1);
3573  }
3574 
3575  // workers - 1: account for city center
3576  repair = city_size_get(pcity) - sp_count - (workers - 1);
3577  if (0 != repair) {
3578  log_sg("[%s] size mismatch for '%s' (%d,%d): size [%d] != "
3579  "(workers [%d] - 1 + specialists [%d]",
3580  citystr, city_name_get(pcity), TILE_XY(city_tile(pcity)),
3581  city_size_get(pcity), workers, sp_count);
3582 
3583  // repair pcity
3584  city_repair_size(pcity, repair);
3585  }
3586 
3587  // worklist_init() done in create_city_virtual()
3588  worklist_load(loading->file, &pcity->worklist, "%s", citystr);
3589 
3590  // Load city options.
3591  BV_CLR_ALL(pcity->city_options);
3592  for (i = 0; i < CITYO_LAST; i++) {
3593  if (secfile_lookup_bool_default(loading->file, false, "%s.option%d",
3594  citystr, i)) {
3595  BV_SET(pcity->city_options, i);
3596  }
3597  }
3598 
3599  CALL_FUNC_EACH_AI(city_load, loading->file, pcity, citystr);
3600 
3601  return true;
3602 }
3603 
3607 static void sg_load_player_city_citizens(struct loaddata *loading,
3608  struct player *plr,
3609  struct city *pcity,
3610  const char *citystr)
3611 {
3612  if (game.info.citizen_nationality) {
3613  citizens size;
3614 
3615  citizens_init(pcity);
3616  player_slots_iterate(pslot)
3617  {
3618  int nationality;
3619 
3620  nationality =
3621  secfile_lookup_int_default(loading->file, -1, "%s.citizen%d",
3622  citystr, player_slot_index(pslot));
3623  if (nationality > 0 && !player_slot_is_used(pslot)) {
3624  log_sg("Citizens of an invalid nation for %s (player slot %d)!",
3625  city_name_get(pcity), player_slot_index(pslot));
3626  continue;
3627  }
3628 
3629  if (nationality != -1 && player_slot_is_used(pslot)) {
3631  "Invalid value for citizens of player %d in %s: %d.",
3632  player_slot_index(pslot), city_name_get(pcity), nationality);
3633  citizens_nation_set(pcity, pslot, nationality);
3634  }
3635  }
3637  // Sanity check.
3638  size = citizens_count(pcity);
3639  if (size != city_size_get(pcity)) {
3640  if (size != 0) {
3641  /* size == 0 can be result from the fact that ruleset had no
3642  * nationality enabled at saving time, so no citizens at all
3643  * were saved. But something more serious must be going on if
3644  * citizens have been saved partially - if some of them are there. */
3645  log_sg("City size and number of citizens does not match in %s "
3646  "(%d != %d)! Repairing ...",
3647  city_name_get(pcity), city_size_get(pcity), size);
3648  }
3649  citizens_update(pcity, nullptr);
3650  }
3651  }
3652 }
3653 
3657 static void sg_load_player_units(struct loaddata *loading,
3658  struct player *plr)
3659 {
3660  int nunits, i, plrno = player_number(plr);
3661 
3662  // Check status and return if not OK (sg_success != TRUE).
3663  sg_check_ret();
3664 
3666  secfile_lookup_int(loading->file, &nunits, "player%d.nunits", plrno),
3667  "%s", secfile_error());
3668  if (!plr->is_alive && nunits > 0) {
3669  log_sg("'player%d.nunits' = %d for dead player!", plrno, nunits);
3670  nunits = 0; // Some old savegames may be buggy.
3671  }
3672 
3673  for (i = 0; i < nunits; i++) {
3674  struct unit *punit;
3675  struct city *pcity;
3676  const char *name;
3677  char buf[32];
3678  struct unit_type *type;
3679  struct tile *ptile;
3680 
3681  fc_snprintf(buf, sizeof(buf), "player%d.u%d", plrno, i);
3682 
3683  name = secfile_lookup_str(loading->file, "%s.type_by_name", buf);
3684  type = unit_type_by_rule_name(name);
3685  sg_failure_ret(type != nullptr, "%s: unknown unit type \"%s\".", buf,
3686  name);
3687 
3688  // Create a dummy unit.
3689  punit = unit_virtual_create(plr, nullptr, type, 0);
3690  if (!sg_load_player_unit(loading, plr, punit, buf)) {
3691  unit_virtual_destroy(punit);
3692  sg_failure_ret(false, "Error loading unit %d of player %d.", i, plrno);
3693  }
3694 
3695  identity_number_reserve(punit->id);
3696  idex_register_unit(&wld, punit);
3697 
3698  if ((pcity = game_city_by_number(punit->homecity))) {
3699  unit_list_prepend(pcity->units_supported, punit);
3700  } else if (punit->homecity > IDENTITY_NUMBER_ZERO) {
3701  log_sg("%s: bad home city %d.", buf, punit->homecity);
3702  punit->homecity = IDENTITY_NUMBER_ZERO;
3703  }
3704 
3705  ptile = unit_tile(punit);
3706 
3707  // allocate the unit's contribution to fog of war
3708  punit->server.vision = vision_new(unit_owner(punit), ptile);
3709  unit_refresh_vision(punit);
3710  /* NOTE: There used to be some map_set_known calls here. These were
3711  * unneeded since unfogging the tile when the unit sees it will
3712  * automatically reveal that tile. */
3713 
3714  unit_list_append(plr->units, punit);
3715  unit_list_prepend(unit_tile(punit)->units, punit);
3716 
3717  // Claim ownership of fortress?
3718  if ((extra_owner(ptile) == nullptr
3719  || pplayers_at_war(extra_owner(ptile), plr))
3720  && tile_has_claimable_base(ptile, unit_type_get(punit))) {
3721  tile_claim_bases(ptile, plr);
3722  }
3723  }
3724 }
3725 
3729 static bool sg_load_player_unit(struct loaddata *loading, struct player *plr,
3730  struct unit *punit, const char *unitstr)
3731 {
3732  int j;
3733  enum unit_activity activity;
3734  int nat_x, nat_y;
3735  enum tile_special_type target;
3736  struct extra_type *pextra = nullptr;
3737  struct base_type *pbase = nullptr;
3738  struct road_type *proad = nullptr;
3739  struct tile *ptile;
3740  int extra_id;
3741  int base_id;
3742  int road_id;
3743  int ei;
3744  const char *facing_str;
3745  enum tile_special_type cfspe;
3746  int natnbr;
3747  bool ai_controlled;
3748 
3750  secfile_lookup_int(loading->file, &punit->id, "%s.id", unitstr), false,
3751  "%s", secfile_error());
3752  sg_warn_ret_val(secfile_lookup_int(loading->file, &nat_x, "%s.x", unitstr),
3753  false, "%s", secfile_error());
3754  sg_warn_ret_val(secfile_lookup_int(loading->file, &nat_y, "%s.y", unitstr),
3755  false, "%s", secfile_error());
3756 
3757  ptile = native_pos_to_tile(&(wld.map), nat_x, nat_y);
3758  sg_warn_ret_val(nullptr != ptile, false, "%s invalid tile (%d, %d)",
3759  unitstr, nat_x, nat_y);
3760  unit_tile_set(punit, ptile);
3761 
3762  facing_str =
3763  secfile_lookup_str_default(loading->file, "x", "%s.facing", unitstr);
3764  if (facing_str[0] != 'x') {
3765  /* We don't touch punit->facing if savegame does not contain that
3766  * information. Initial orientation set by unit_virtual_create()
3767  * is as good as any. */
3768  enum direction8 facing = char2dir(facing_str[0]);
3769 
3770  if (direction8_is_valid(facing)) {
3771  punit->facing = facing;
3772  } else {
3773  qCritical("Illegal unit orientation '%s'", facing_str);
3774  }
3775  }
3776 
3777  /* If savegame has unit nationality, it doesn't hurt to
3778  * internally set it even if nationality rules are disabled. */
3779  natnbr = secfile_lookup_int_default(loading->file, player_number(plr),
3780  "%s.nationality", unitstr);
3781 
3782  punit->nationality = player_by_number(natnbr);
3783  if (punit->nationality == nullptr) {
3784  punit->nationality = plr;
3785  }
3786 
3787  sg_warn_ret_val(secfile_lookup_int(loading->file, &punit->homecity,
3788  "%s.homecity", unitstr),
3789  false, "%s", secfile_error());
3791  "%s.moves", unitstr),
3792  false, "%s", secfile_error());
3794  secfile_lookup_int(loading->file, &punit->fuel, "%s.fuel", unitstr),
3795  false, "%s", secfile_error());
3797  secfile_lookup_int(loading->file, &ei, "%s.activity", unitstr), false,
3798  "%s", secfile_error());
3799  activity =
3800  unit_activity_by_name(loading->activities.order[ei], fc_strcasecmp);
3801 
3802  punit->server.birth_turn = secfile_lookup_int_default(
3803  loading->file, game.info.turn, "%s.born", unitstr);
3804 
3805  if (activity == ACTIVITY_PATROL_UNUSED) {
3806  /* Previously ACTIVITY_PATROL and ACTIVITY_GOTO were used for
3807  * client-side goto. Now client-side goto is handled by setting
3808  * a special flag, and units with orders generally have ACTIVITY_IDLE.
3809  * Old orders are lost. Old client-side goto units will still have
3810  * ACTIVITY_GOTO and will goto the correct position via server goto.
3811  * Old client-side patrol units lose their patrol routes and are put
3812  * into idle mode. */
3813  activity = ACTIVITY_IDLE;
3814  }
3815 
3816  extra_id = secfile_lookup_int_default(loading->file, -2, "%s.activity_tgt",
3817  unitstr);
3818 
3819  if (extra_id != -2) {
3820  if (extra_id >= 0 && extra_id < loading->extra.size) {
3821  pextra = loading->extra.order[extra_id];
3822  set_unit_activity_targeted(punit, activity, pextra);
3823  } else if (activity == ACTIVITY_IRRIGATE) {
3824  struct extra_type *tgt = next_extra_for_tile(
3825  unit_tile(punit), EC_IRRIGATION, unit_owner(punit), punit);
3826  if (tgt != nullptr) {
3827  set_unit_activity_targeted(punit, ACTIVITY_IRRIGATE, tgt);
3828  } else {
3829  set_unit_activity(punit, ACTIVITY_CULTIVATE);
3830  }
3831  } else if (activity == ACTIVITY_MINE) {
3832  struct extra_type *tgt = next_extra_for_tile(unit_tile(punit), EC_MINE,
3833  unit_owner(punit), punit);
3834  if (tgt != nullptr) {
3835  set_unit_activity_targeted(punit, ACTIVITY_MINE, tgt);
3836  } else {
3837  set_unit_activity(punit, ACTIVITY_PLANT);
3838  }
3839  } else {
3840  set_unit_activity(punit, activity);
3841  }
3842  } else {
3843  // extra_id == -2 -> activity_tgt not set
3844  base_id = secfile_lookup_int_default(loading->file, -1,
3845  "%s.activity_base", unitstr);
3846  if (base_id >= 0 && base_id < loading->base.size) {
3847  pbase = loading->base.order[base_id];
3848  }
3849  road_id = secfile_lookup_int_default(loading->file, -1,
3850  "%s.activity_road", unitstr);
3851  if (road_id >= 0 && road_id < loading->road.size) {
3852  proad = loading->road.order[road_id];
3853  }
3854 
3855  {
3856  int tgt_no = secfile_lookup_int_default(
3857  loading->file, loading->special.size /* S_LAST */,
3858  "%s.activity_target", unitstr);
3859  if (tgt_no >= 0 && tgt_no < loading->special.size) {
3860  target = loading->special.order[tgt_no];
3861  } else {
3862  target = S_LAST;
3863  }
3864  }
3865 
3866  if (target == S_OLD_ROAD) {
3867  target = S_LAST;
3869  } else if (target == S_OLD_RAILROAD) {
3870  target = S_LAST;
3872  }
3873 
3874  if (activity == ACTIVITY_OLD_ROAD) {
3875  activity = ACTIVITY_GEN_ROAD;
3877  } else if (activity == ACTIVITY_OLD_RAILROAD) {
3878  activity = ACTIVITY_GEN_ROAD;
3880  }
3881 
3882  /* We need changed_from == ACTIVITY_IDLE by now so that
3883  * set_unit_activity() and friends don't spuriously restore activity
3884  * points -- unit should have been created this way */
3885  fc_assert(punit->changed_from == ACTIVITY_IDLE);
3886 
3887  if (activity == ACTIVITY_BASE) {
3888  if (pbase) {
3889  set_unit_activity_base(punit, base_number(pbase));
3890  } else {
3891  log_sg("Cannot find base %d for %s to build", base_id,
3892  unit_rule_name(punit));
3893  set_unit_activity(punit, ACTIVITY_IDLE);
3894  }
3895  } else if (activity == ACTIVITY_GEN_ROAD) {
3896  if (proad) {
3897  set_unit_activity_road(punit, road_number(proad));
3898  } else {
3899  log_sg("Cannot find road %d for %s to build", road_id,
3900  unit_rule_name(punit));
3901  set_unit_activity(punit, ACTIVITY_IDLE);
3902  }
3903  } else if (activity == ACTIVITY_PILLAGE) {
3904  struct extra_type *a_target;
3905 
3906  if (target != S_LAST) {
3907  a_target = special_extra_get(target);
3908  } else if (pbase != nullptr) {
3909  a_target = base_extra_get(pbase);
3910  } else if (proad != nullptr) {
3911  a_target = road_extra_get(proad);
3912  } else {
3913  a_target = nullptr;
3914  }
3915  /* An out-of-range base number is seen with old savegames. We take
3916  * it as indicating undirected pillaging. We will assign pillage
3917  * targets before play starts. */
3918  set_unit_activity_targeted(punit, activity, a_target);
3919  } else if (activity == ACTIVITY_IRRIGATE) {
3920  struct extra_type *tgt = next_extra_for_tile(
3921  unit_tile(punit), EC_IRRIGATION, unit_owner(punit), punit);
3922  if (tgt != nullptr) {
3923  set_unit_activity_targeted(punit, ACTIVITY_IRRIGATE, tgt);
3924  } else {
3925  set_unit_activity_targeted(punit, ACTIVITY_IRRIGATE, nullptr);
3926  }
3927  } else if (activity == ACTIVITY_MINE) {
3928  struct extra_type *tgt = next_extra_for_tile(unit_tile(punit), EC_MINE,
3929  unit_owner(punit), punit);
3930  if (tgt != nullptr) {
3931  set_unit_activity_targeted(punit, ACTIVITY_MINE, tgt);
3932  } else {
3933  set_unit_activity_targeted(punit, ACTIVITY_MINE, nullptr);
3934  }
3935  } else if (activity == ACTIVITY_POLLUTION) {
3936  struct extra_type *tgt = prev_extra_in_tile(
3937  unit_tile(punit), ERM_CLEANPOLLUTION, unit_owner(punit), punit);
3938  if (tgt != nullptr) {
3939  set_unit_activity_targeted(punit, ACTIVITY_POLLUTION, tgt);
3940  } else {
3941  set_unit_activity_targeted(punit, ACTIVITY_POLLUTION, nullptr);
3942  }
3943  } else if (activity == ACTIVITY_FALLOUT) {
3944  struct extra_type *tgt = prev_extra_in_tile(
3945  unit_tile(punit), ERM_CLEANFALLOUT, unit_owner(punit), punit);
3946  if (tgt != nullptr) {
3947  set_unit_activity_targeted(punit, ACTIVITY_FALLOUT, tgt);
3948  } else {
3949  set_unit_activity_targeted(punit, ACTIVITY_FALLOUT, nullptr);
3950  }
3951  } else {
3952  set_unit_activity_targeted(punit, activity, nullptr);
3953  }
3954  } // activity_tgt == nullptr
3955 
3957  "%s.activity_count", unitstr),
3958  false, "%s", secfile_error());
3959 
3960  punit->changed_from =
3961  static_cast<unit_activity>(secfile_lookup_int_default(
3962  loading->file, ACTIVITY_IDLE, "%s.changed_from", unitstr));
3963 
3964  extra_id = secfile_lookup_int_default(loading->file, -2,
3965  "%s.changed_from_tgt", unitstr);
3966 
3967  if (extra_id != -2) {
3968  if (extra_id >= 0 && extra_id < loading->extra.size) {
3969  punit->changed_from_target = loading->extra.order[extra_id];
3970  } else {
3971  punit->changed_from_target = nullptr;
3972  }
3973  } else {
3974  // extra_id == -2 -> changed_from_tgt not set
3975 
3976  cfspe = static_cast<tile_special_type>(secfile_lookup_int_default(
3977  loading->file, S_LAST, "%s.changed_from_target", unitstr));
3978  base_id = secfile_lookup_int_default(loading->file, -1,
3979  "%s.changed_from_base", unitstr);
3980  road_id = secfile_lookup_int_default(loading->file, -1,
3981  "%s.changed_from_road", unitstr);
3982 
3983  if (road_id == -1) {
3984  if (cfspe == S_OLD_ROAD) {
3986  if (proad) {
3987  road_id = road_number(proad);
3988  }
3989  } else if (cfspe == S_OLD_RAILROAD) {
3991  if (proad) {
3992  road_id = road_number(proad);
3993  }
3994  }
3995  }
3996 
3997  if (base_id >= 0 && base_id < loading->base.size) {
3998  punit->changed_from_target =
3999  base_extra_get(loading->base.order[base_id]);
4000  } else if (road_id >= 0 && road_id < loading->road.size) {
4001  punit->changed_from_target =
4002  road_extra_get(loading->road.order[road_id]);
4003  } else if (cfspe != S_LAST) {
4004  punit->changed_from_target = special_extra_get(cfspe);
4005  } else {
4006  punit->changed_from_target = nullptr;
4007  }
4008 
4009  if (punit->changed_from == ACTIVITY_IRRIGATE) {
4010  struct extra_type *tgt = next_extra_for_tile(
4011  unit_tile(punit), EC_IRRIGATION, unit_owner(punit), punit);
4012  if (tgt != nullptr) {
4013  punit->changed_from_target = tgt;
4014  } else {
4015  punit->changed_from_target = nullptr;
4016  }
4017  } else if (punit->changed_from == ACTIVITY_MINE) {
4018  struct extra_type *tgt = next_extra_for_tile(unit_tile(punit), EC_MINE,
4019  unit_owner(punit), punit);
4020  if (tgt != nullptr) {
4021  punit->changed_from_target = tgt;
4022  } else {
4023  punit->changed_from_target = nullptr;
4024  }
4025  } else if (punit->changed_from == ACTIVITY_POLLUTION) {
4026  struct extra_type *tgt = prev_extra_in_tile(
4027  unit_tile(punit), ERM_CLEANPOLLUTION, unit_owner(punit), punit);
4028  if (tgt != nullptr) {
4029  punit->changed_from_target = tgt;
4030  } else {
4031  punit->changed_from_target = nullptr;
4032  }
4033  } else if (punit->changed_from == ACTIVITY_FALLOUT) {
4034  struct extra_type *tgt = prev_extra_in_tile(
4035  unit_tile(punit), ERM_CLEANFALLOUT, unit_owner(punit), punit);
4036  if (tgt != nullptr) {
4037  punit->changed_from_target = tgt;
4038  } else {
4039  punit->changed_from_target = nullptr;
4040  }
4041  }
4042  }
4043 
4045  loading->file, 0, "%s.changed_from_count", unitstr);
4046 
4047  /* Special case: for a long time, we accidentally incremented
4048  * activity_count while a unit was sentried, so it could increase
4049  * without bound (bug #20641) and be saved in old savefiles.
4050  * We zero it to prevent potential trouble overflowing the range
4051  * in network packets, etc. */
4052  if (activity == ACTIVITY_SENTRY) {
4053  punit->activity_count = 0;
4054  }
4055  if (punit->changed_from == ACTIVITY_SENTRY) {
4056  punit->changed_from_count = 0;
4057  }
4058 
4059  punit->veteran =
4060  secfile_lookup_int_default(loading->file, 0, "%s.veteran", unitstr);
4061  {
4062  // Protect against change in veteran system in ruleset
4063  const int levels = utype_veteran_levels(unit_type_get(punit));
4064  if (punit->veteran >= levels) {
4065  fc_assert(levels >= 1);
4066  punit->veteran = levels - 1;
4067  }
4068  }
4070  loading->file, (punit->moves_left == 0), "%s.done_moving", unitstr);
4072  loading->file, BATTLEGROUP_NONE, "%s.battlegroup", unitstr);
4073 
4074  if (secfile_lookup_bool_default(loading->file, false, "%s.go", unitstr)) {
4075  int gnat_x, gnat_y;
4076 
4078  secfile_lookup_int(loading->file, &gnat_x, "%s.goto_x", unitstr),
4079  false, "%s", secfile_error());
4081  secfile_lookup_int(loading->file, &gnat_y, "%s.goto_y", unitstr),
4082  false, "%s", secfile_error());
4083 
4084  punit->goto_tile = native_pos_to_tile(&(wld.map), gnat_x, gnat_y);
4085  } else {
4086  punit->goto_tile = nullptr;
4087 
4088  /* These variables are not used but needed for saving the unit table.
4089  * Load them to prevent unused variables errors. */
4090  (void) secfile_entry_lookup(loading->file, "%s.goto_x", unitstr);
4091  (void) secfile_entry_lookup(loading->file, "%s.goto_y", unitstr);
4092  }
4093 
4094  // Load AI data of the unit.
4095  CALL_FUNC_EACH_AI(unit_load, loading->file, punit, unitstr);
4096 
4098  secfile_lookup_bool(loading->file, &ai_controlled, "%s.ai", unitstr),
4099  false, "%s", secfile_error());
4100  if (ai_controlled) {
4101  /* Autosettler and Auotexplore are separated by
4102  * compat_post_load_030100() when set to SSA_AUTOSETTLER */
4103  punit->ssa_controller = SSA_AUTOSETTLER;
4104  } else {
4105  punit->ssa_controller = SSA_NONE;
4106  }
4108  secfile_lookup_int(loading->file, &punit->hp, "%s.hp", unitstr), false,
4109  "%s", secfile_error());
4110 
4111  punit->server.ord_map =
4112  secfile_lookup_int_default(loading->file, 0, "%s.ord_map", unitstr);
4113  punit->server.ord_city =
4114  secfile_lookup_int_default(loading->file, 0, "%s.ord_city", unitstr);
4115  punit->moved =
4116  secfile_lookup_bool_default(loading->file, false, "%s.moved", unitstr);
4118  loading->file, false, "%s.paradropped", unitstr);
4119 
4120  /* The transport status (punit->transported_by) is loaded in
4121  * sg_player_units_transport(). */
4122 
4123  /* Initialize upkeep values: these are hopefully initialized
4124  * elsewhere before use (specifically, in city_support(); but
4125  * fixme: check whether always correctly initialized?).
4126  * Below is mainly for units which don't have homecity --
4127  * otherwise these don't get initialized (and AI calculations
4128  * etc may use junk values). */
4130  {
4131  punit->upkeep[o] = utype_upkeep_cost(unit_type_get(punit), plr,
4132  static_cast<Output_type_id>(o));
4133  }
4135 
4136  punit->action_decision_want =
4137  static_cast<action_decision>(secfile_lookup_enum_default(
4138  loading->file, ACT_DEC_NOTHING, action_decision,
4139  "%s.action_decision_want", unitstr));
4140 
4141  if (punit->action_decision_want != ACT_DEC_NOTHING) {
4142  // Load the tile to act against.
4143  int adwt_x, adwt_y;
4144 
4145  if (secfile_lookup_int(loading->file, &adwt_x,
4146  "%s.action_decision_tile_x", unitstr)
4147  && secfile_lookup_int(loading->file, &adwt_y,
4148  "%s.action_decision_tile_y", unitstr)) {
4149  punit->action_decision_tile =
4150  native_pos_to_tile(&(wld.map), adwt_x, adwt_y);
4151  } else {
4152  punit->action_decision_want = ACT_DEC_NOTHING;
4153  punit->action_decision_tile = nullptr;
4154  log_sg("Bad action_decision_tile for unit %d", punit->id);
4155  }
4156  } else {
4157  (void) secfile_entry_lookup(loading->file, "%s.action_decision_tile_x",
4158  unitstr);
4159  (void) secfile_entry_lookup(loading->file, "%s.action_decision_tile_y",
4160  unitstr);
4161  punit->action_decision_tile = nullptr;
4162  }
4163 
4164  // load the unit orders
4165  {
4166  int len = secfile_lookup_int_default(loading->file, 0,
4167  "%s.orders_length", unitstr);
4168  if (len > 0) {
4169  const char *orders_unitstr, *dir_unitstr, *act_unitstr;
4170  const char *tgt_unitstr;
4171  const char *base_unitstr = nullptr;
4172  const char *road_unitstr = nullptr;
4173  int road_idx = road_number(road_by_compat_special(ROCO_ROAD));
4175 
4176  punit->orders.list = new unit_order[len];
4177  punit->orders.length = len;
4179  loading->file, 0, "%s.orders_index", unitstr);
4181  loading->file, false, "%s.orders_repeat", unitstr);
4183  loading->file, false, "%s.orders_vigilant", unitstr);
4184 
4185  orders_unitstr = secfile_lookup_str_default(loading->file, "",
4186  "%s.orders_list", unitstr);
4187  dir_unitstr = secfile_lookup_str_default(loading->file, "",
4188  "%s.dir_list", unitstr);
4189  act_unitstr = secfile_lookup_str_default(loading->file, "",
4190  "%s.activity_list", unitstr);
4191  tgt_unitstr = secfile_lookup_str_default(loading->file, nullptr,
4192  "%s.tgt_list", unitstr);
4193 
4194  if (tgt_unitstr == nullptr) {
4195  base_unitstr =
4196  secfile_lookup_str(loading->file, "%s.base_list", unitstr);
4197  road_unitstr = secfile_lookup_str_default(loading->file, nullptr,
4198  "%s.road_list", unitstr);
4199  }
4200 
4201  punit->has_orders = true;
4202  for (j = 0; j < len; j++) {
4203  struct unit_order *order = &punit->orders.list[j];
4204 
4205  if (orders_unitstr[j] == '\0' || dir_unitstr[j] == '\0'
4206  || act_unitstr[j] == '\0') {
4207  log_sg("Invalid unit orders.");
4208  free_unit_orders(punit);
4209  break;
4210  }
4211  order->order = char2order(orders_unitstr[j]);
4212  order->dir = char2dir(dir_unitstr[j]);
4213  order->activity = char2activity(act_unitstr[j]);
4214  // Target, if needed, is set in compat_post_load_030100()
4215  order->target = NO_TARGET;
4216  order->sub_target = NO_TARGET;
4217 
4218  if (order->order == ORDER_LAST
4219  || (order->order == ORDER_MOVE
4220  && !direction8_is_valid(order->dir))
4221  || (order->order == ORDER_ACTION_MOVE
4222  && !direction8_is_valid(order->dir))
4223  || (order->order == ORDER_ACTIVITY
4224  && order->activity == ACTIVITY_LAST)) {
4225  // An invalid order. Just drop the orders for this unit.
4226  delete[] punit->orders.list;
4227  punit->orders.list = nullptr;
4228  punit->has_orders = false;
4229  break;
4230  }
4231 
4232  // The order may have been replaced by the perform action order
4233  order->action =
4234  sg_order_to_action(order->order, punit, punit->goto_tile);
4235  if (order->action != ACTION_NONE) {
4236  // The order was converted by order_to_action
4237  order->order = ORDER_PERFORM_ACTION;
4238  }
4239 
4240  if (tgt_unitstr) {
4241  if (tgt_unitstr[j] != '?') {
4242  extra_id = char2num(tgt_unitstr[j]);
4243 
4244  if (extra_id < 0 || extra_id >= loading->extra.size) {
4245  log_sg("Cannot find extra %d for %s to build", extra_id,
4246  unit_rule_name(punit));
4247  order->sub_target = EXTRA_NONE;
4248  } else {
4249  order->sub_target = extra_id;
4250  }
4251  } else {
4252  order->sub_target = EXTRA_NONE;
4253  }
4254  } else {
4255  /* In pre-2.6 savegames, base_list and road_list were only saved
4256  * for those activities (and not e.g. pillaging) */
4257  if (base_unitstr && base_unitstr[j] != '?'
4258  && order->activity == ACTIVITY_BASE) {
4259  base_id = char2num(base_unitstr[j]);
4260 
4261  if (base_id < 0 || base_id >= loading->base.size) {
4262  log_sg("Cannot find base %d for %s to build", base_id,
4263  unit_rule_name(punit));
4264  base_id = base_number(
4265  get_base_by_gui_type(BASE_GUI_FORTRESS, nullptr, nullptr));
4266  }
4267 
4268  order->sub_target =
4270  } else if (road_unitstr && road_unitstr[j] != '?'
4271  && order->activity == ACTIVITY_GEN_ROAD) {
4272  road_id = char2num(road_unitstr[j]);
4273 
4274  if (road_id < 0 || road_id >= loading->road.size) {
4275  log_sg("Cannot find road %d for %s to build", road_id,
4276  unit_rule_name(punit));
4277  road_id = 0;
4278  }
4279 
4280  order->sub_target =
4282  } else {
4283  order->sub_target = EXTRA_NONE;
4284  }
4285 
4286  if (order->activity == ACTIVITY_OLD_ROAD) {
4287  order->activity = ACTIVITY_GEN_ROAD;
4288  order->sub_target =
4290  } else if (order->activity == ACTIVITY_OLD_RAILROAD) {
4291  order->activity = ACTIVITY_GEN_ROAD;
4292  order->sub_target =
4294  }
4295  }
4296  }
4297  } else {
4298  punit->has_orders = false;
4299  punit->orders.list = nullptr;
4300 
4301  (void) secfile_entry_lookup(loading->file, "%s.orders_index", unitstr);
4302  (void) secfile_entry_lookup(loading->file, "%s.orders_repeat",
4303  unitstr);
4304  (void) secfile_entry_lookup(loading->file, "%s.orders_vigilant",
4305  unitstr);
4306  (void) secfile_entry_lookup(loading->file, "%s.orders_list", unitstr);
4307  (void) secfile_entry_lookup(loading->file, "%s.dir_list", unitstr);
4308  (void) secfile_entry_lookup(loading->file, "%s.activity_list",
4309  unitstr);
4310  (void) secfile_entry_lookup(loading->file, "%s.tgt_list", unitstr);
4311  }
4312  }
4313 
4314  return true;
4315 }
4316 
4321 static void sg_load_player_units_transport(struct loaddata *loading,
4322  struct player *plr)
4323 {
4324  int nunits, i, plrno = player_number(plr);
4325 
4326  // Check status and return if not OK (sg_success != TRUE).
4327  sg_check_ret();
4328 
4329  /* Recheck the number of units for the player. This is a copied from
4330  * sg_load_player_units(). */
4332  secfile_lookup_int(loading->file, &nunits, "player%d.nunits", plrno),
4333  "%s", secfile_error());
4334  if (!plr->is_alive && nunits > 0) {
4335  log_sg("'player%d.nunits' = %d for dead player!", plrno, nunits);
4336  nunits = 0; // Some old savegames may be buggy.
4337  }
4338 
4339  for (i = 0; i < nunits; i++) {
4340  int id_unit, id_trans;
4341  struct unit *punit, *ptrans;
4342 
4343  id_unit = secfile_lookup_int_default(loading->file, -1,
4344  "player%d.u%d.id", plrno, i);
4345  punit = player_unit_by_number(plr, id_unit);
4346  fc_assert_action(punit != nullptr, continue);
4347 
4348  id_trans = secfile_lookup_int_default(
4349  loading->file, -1, "player%d.u%d.transported_by", plrno, i);
4350  if (id_trans == -1) {
4351  // Not transported.
4352  continue;
4353  }
4354 
4355  ptrans = game_unit_by_number(id_trans);
4356  fc_assert_action(id_trans == -1 || ptrans != nullptr, continue);
4357 
4358  if (ptrans) {
4359  bool load_success = unit_transport_load(punit, ptrans, true);
4360 
4361  fc_assert_action(load_success == true, continue);
4362  }
4363  }
4364 }
4365 
4369 static void sg_load_player_attributes(struct loaddata *loading,
4370  struct player *plr)
4371 {
4372  int plrno = player_number(plr);
4373 
4374  // Check status and return if not OK (sg_success != TRUE).
4375  sg_check_ret();
4376 
4377  // Toss any existing attribute_block (should not exist)
4378  plr->attribute_block.clear();
4379 
4380  // This is a big heap of opaque data for the client, check everything!
4382  loading->file, 0, "player%d.attribute_v2_block_length", plrno);
4383 
4384  if (length < 0) {
4385  log_sg("player%d.attribute_v2_block_length=%d too small", plrno, length);
4386  } else if (length >= MAX_ATTRIBUTE_BLOCK) {
4387  log_sg("player%d.attribute_v2_block_length=%d too big (max %d)", plrno,
4389  } else if (length > 0) {
4390  int part_nr, parts;
4391  size_t actual_length;
4392  int quoted_length;
4393  char *quoted;
4394 
4396  loading->file, &quoted_length,
4397  "player%d.attribute_v2_block_length_quoted", plrno),
4398  "%s", secfile_error());
4400  "player%d.attribute_v2_block_parts",
4401  plrno),
4402  "%s", secfile_error());
4403 
4404  quoted = new char[quoted_length + 1];
4405  quoted[0] = '\0';
4406  plr->attribute_block.resize(length);
4407  for (part_nr = 0; part_nr < parts; part_nr++) {
4408  const char *current = secfile_lookup_str(
4409  loading->file, "player%d.attribute_v2_block_data.part%d", plrno,
4410  part_nr);
4411  if (!current) {
4412  log_sg("attribute_v2_block_parts=%d actual=%d", parts, part_nr);
4413  break;
4414  }
4415  log_debug("attribute_v2_block_length_quoted=%lu have=%lu part=%lu",
4416  (unsigned long) quoted_length,
4417  (unsigned long) qstrlen(quoted),
4418  (unsigned long) qstrlen(current));
4419  fc_assert(strlen(quoted) + qstrlen(current) <= quoted_length);
4420  strcat(quoted, current);
4421  }
4422  fc_assert_msg(quoted_length == qstrlen(quoted),
4423  "attribute_v2_block_length_quoted=%lu actual=%lu",
4424  (unsigned long) quoted_length,
4425  (unsigned long) qstrlen(quoted));
4426 
4427  actual_length = unquote_block(quoted, plr->attribute_block.data(),
4428  plr->attribute_block.size());
4429  fc_assert(actual_length == plr->attribute_block.size());
4430  delete[] quoted;
4431  }
4432 }
4433 
4437 static void sg_load_player_vision(struct loaddata *loading,
4438  struct player *plr)
4439 {
4440  int plrno = player_number(plr);
4441  int total_ncities = secfile_lookup_int_default(loading->file, -1,
4442  "player%d.dc_total", plrno);
4443  int i;
4444  bool someone_alive = false;
4445 
4446  // Check status and return if not OK (sg_success != TRUE).
4447  sg_check_ret();
4448 
4449  if (game.server.revealmap & REVEAL_MAP_DEAD) {
4450  player_list_iterate(team_members(plr->team), pteam_member)
4451  {
4452  if (pteam_member->is_alive) {
4453  someone_alive = true;
4454  break;
4455  }
4456  }
4458 
4459  if (!someone_alive) {
4460  // Reveal all for completely dead teams.
4461  map_know_and_see_all(plr);
4462  }
4463  }
4464 
4465  if (!plr->is_alive || -1 == total_ncities || !game.info.fogofwar
4466  || !secfile_lookup_bool_default(loading->file, true,
4467  "game.save_private_map")) {
4468  /* We have:
4469  * - a dead player;
4470  * - fogged cities are not saved for any reason;
4471  * - a savegame with fog of war turned off;
4472  * - or game.save_private_map is not set to FALSE in the scenario /
4473  * savegame. The players private knowledge is set to be what he could
4474  * see without fog of war. */
4475  whole_map_iterate(&(wld.map), ptile)
4476  {
4477  if (map_is_known(ptile, plr)) {
4478  struct city *pcity = tile_city(ptile);
4479 
4480  update_player_tile_last_seen(plr, ptile);
4481  update_player_tile_knowledge(plr, ptile);
4482 
4483  if (nullptr != pcity) {
4484  update_dumb_city(plr, pcity);
4485  }
4486  }
4487  }
4489 
4490  // Nothing more to do;
4491  return;
4492  }
4493 
4494  // Load player map (terrain).
4495  LOAD_MAP_CHAR(ch, ptile,
4496  map_get_player_tile(ptile, plr)->terrain = char2terrain(ch),
4497  loading->file, "player%d.map_t%04d", plrno);
4498 
4499  // Load player map (resources).
4500  LOAD_MAP_CHAR(ch, ptile,
4501  map_get_player_tile(ptile, plr)->resource =
4502  char2resource(ch),
4503  loading->file, "player%d.map_res%04d", plrno);
4504 
4505  if (loading->version >= 30) {
4506  // 2.6.0 or newer
4507 
4508  // Load player map (extras).
4509  halfbyte_iterate_extras(j, loading->extra.size)
4510  {
4511  LOAD_MAP_CHAR(ch, ptile,
4513  ch, loading->extra.order + 4 * j),
4514  loading->file, "player%d.map_e%02d_%04d", plrno, j);
4515  }
4517  } else {
4518  // Load player map (specials).
4520  {
4521  LOAD_MAP_CHAR(
4522  ch, ptile,
4523  sg_special_set(ptile, &map_get_player_tile(ptile, plr)->extras, ch,
4524  loading->special.order + 4 * static_cast<int>(x),
4525  false),
4526  loading->file, "player%d.map_spe%02d_%04d", plrno, x);
4527  }
4529 
4530  // Load player map (bases).
4531  halfbyte_iterate_bases(j, loading->base.size)
4532  {
4533  LOAD_MAP_CHAR(ch, ptile,
4534  sg_bases_set(&map_get_player_tile(ptile, plr)->extras,
4535  ch, loading->base.order + 4 * j),
4536  loading->file, "player%d.map_b%02d_%04d", plrno, j);
4537  }
4539 
4540  // Load player map (roads).
4541  if (loading->version >= 20) {
4542  // 2.5.0 or newer
4543  halfbyte_iterate_roads(j, loading->road.size)
4544  {
4545  LOAD_MAP_CHAR(ch, ptile,
4546  sg_roads_set(&map_get_player_tile(ptile, plr)->extras,
4547  ch, loading->road.order + 4 * j),
4548  loading->file, "player%d.map_r%02d_%04d", plrno, j);
4549  }
4551  }
4552  }
4553 
4554  if (game.server.foggedborders) {
4555  // Load player map (border).
4556  int x, y;
4557 
4558  for (y = 0; y < wld.map.ysize; y++) {
4559  const char *buffer = secfile_lookup_str(
4560  loading->file, "player%d.map_owner%04d", plrno, y);
4561  const char *buffer2 = secfile_lookup_str(
4562  loading->file, "player%d.extras_owner%04d", plrno, y);
4563  const char *ptr = buffer;
4564  const char *ptr2 = buffer2;
4565 
4566  sg_failure_ret(nullptr != buffer,
4567  "Savegame corrupt - map line %d not found.", y);
4568  for (x = 0; x < wld.map.xsize; x++) {
4569  char token[TOKEN_SIZE];
4570  char token2[TOKEN_SIZE];
4571  int number;
4572  struct tile *ptile = native_pos_to_tile(&(wld.map), x, y);
4573  char n[] = ",";
4574  scanin(const_cast<char **>(&ptr), n, token, sizeof(token));
4575  sg_failure_ret('\0' != token[0],
4576  "Savegame corrupt - map size not correct.");
4577  if (strcmp(token, "-") == 0) {
4578  map_get_player_tile(ptile, plr)->owner = nullptr;
4579  } else {
4580  sg_failure_ret(str_to_int(token, &number),
4581  "Savegame corrupt - got tile owner=%s in (%d, %d).",
4582  token, x, y);
4583  map_get_player_tile(ptile, plr)->owner = player_by_number(number);
4584  }
4585 
4586  if (loading->version >= 30) {
4587  char n[] = ",";
4588  scanin(const_cast<char **>(&ptr2), n, token2, sizeof(token2));
4589  sg_failure_ret('\0' != token2[0],
4590  "Savegame corrupt - map size not correct.");
4591  if (strcmp(token2, "-") == 0) {
4592  map_get_player_tile(ptile, plr)->extras_owner = nullptr;
4593  } else {
4595  str_to_int(token2, &number),
4596  "Savegame corrupt - got extras owner=%s in (%d, %d).", token,
4597  x, y);
4598  map_get_player_tile(ptile, plr)->extras_owner =
4599  player_by_number(number);
4600  }
4601  } else {
4602  map_get_player_tile(ptile, plr)->extras_owner =
4603  map_get_player_tile(ptile, plr)->owner;
4604  }
4605  }
4606  }
4607  }
4608 
4609  // Load player map (update time).
4610  for (i = 0; i < 4; i++) {
4611  // put 4-bit segments of 16-bit "updated" field
4612  if (i == 0) {
4613  LOAD_MAP_CHAR(ch, ptile,
4614  map_get_player_tile(ptile, plr)->last_updated =
4615  ascii_hex2bin(ch, i),
4616  loading->file, "player%d.map_u%02d_%04d", plrno, i);
4617  } else {
4618  LOAD_MAP_CHAR(ch, ptile,
4619  map_get_player_tile(ptile, plr)->last_updated |=
4620  ascii_hex2bin(ch, i),
4621  loading->file, "player%d.map_u%02d_%04d", plrno, i);
4622  }
4623  }
4624 
4625  // Load player map known cities.
4626  for (i = 0; i < total_ncities; i++) {
4627  struct vision_site *pdcity;
4628  char buf[32];
4629  fc_snprintf(buf, sizeof(buf), "player%d.dc%d", plrno, i);
4630 
4631  pdcity = vision_site_new(0, nullptr, nullptr);
4632  if (sg_load_player_vision_city(loading, plr, pdcity, buf)) {
4634  pdcity);
4636  } else {
4637  // Error loading the data.
4638  log_sg("Skipping seen city %d for player %d.", i, plrno);
4639  delete pdcity;
4640  }
4641  }
4642 
4643  // Repair inconsistent player maps.
4644  whole_map_iterate(&(wld.map), ptile)
4645  {
4646  if (map_is_known_and_seen(ptile, plr, V_MAIN)) {
4647  struct city *pcity = tile_city(ptile);
4648 
4649  update_player_tile_knowledge(plr, ptile);
4650  reality_check_city(plr, ptile);
4651 
4652  if (nullptr != pcity) {
4653  update_dumb_city(plr, pcity);
4654  }
4655  } else if (!game.server.foggedborders && map_is_known(ptile, plr)) {
4656  // Non fogged borders aren't loaded. See hrm Bug #879084
4657  struct player_tile *plrtile = map_get_player_tile(ptile, plr);
4658 
4659  plrtile->owner = tile_owner(ptile);
4660  }
4661  }
4663 }
4664 
4668 static bool sg_load_player_vision_city(struct loaddata *loading,
4669  struct player *plr,
4670  struct vision_site *pdcity,
4671  const char *citystr)
4672 {
4673  const char *string;
4674  int i, id, size;
4675  citizens city_size;
4676  int nat_x, nat_y;
4677  const char *stylename;
4678 
4679  sg_warn_ret_val(secfile_lookup_int(loading->file, &nat_x, "%s.x", citystr),
4680  false, "%s", secfile_error());
4681  sg_warn_ret_val(secfile_lookup_int(loading->file, &nat_y, "%s.y", citystr),
4682  false, "%s", secfile_error());
4683  pdcity->location = native_pos_to_tile(&(wld.map), nat_x, nat_y);
4684  sg_warn_ret_val(nullptr != pdcity->location, false,
4685  "%s invalid tile (%d,%d)", citystr, nat_x, nat_y);
4686 
4688  secfile_lookup_int(loading->file, &id, "%s.owner", citystr), false,
4689  "%s", secfile_error());
4690  pdcity->owner = player_by_number(id);
4691  sg_warn_ret_val(nullptr != pdcity->owner, false,
4692  "%s has invalid owner (%d); skipping.", citystr, id);
4693 
4695  secfile_lookup_int(loading->file, &pdcity->identity, "%s.id", citystr),
4696  false, "%s", secfile_error());
4697  sg_warn_ret_val(IDENTITY_NUMBER_ZERO < pdcity->identity, false,
4698  "%s has invalid id (%d); skipping.", citystr, id);
4699 
4701  secfile_lookup_int(loading->file, &size, "%s.size", citystr), false,
4702  "%s", secfile_error());
4703  city_size = static_cast<citizens>(size); // set the correct type
4704  sg_warn_ret_val(size == (int) city_size, false,
4705  "Invalid city size: %d; set to %d.", size, city_size);
4706  vision_site_size_set(pdcity, city_size);
4707 
4708  // Initialise list of improvements
4709  BV_CLR_ALL(pdcity->improvements);
4710  string = secfile_lookup_str(loading->file, "%s.improvements", citystr);
4711  sg_warn_ret_val(string != nullptr, false, "%s", secfile_error());
4712  sg_warn_ret_val(strlen(string) == loading->improvement.size, false,
4713  "Invalid length of '%s.improvements' (%lu ~= %lu).",
4714  citystr, (unsigned long) qstrlen(string),
4715  (unsigned long) loading->improvement.size);
4716  for (i = 0; i < loading->improvement.size; i++) {
4717  sg_warn_ret_val(string[i] == '1' || string[i] == '0', false,
4718  "Undefined value '%c' within '%s.improvements'.",
4719  string[i], citystr)
4720 
4721  if (string[i] == '1')
4722  {
4723  struct impr_type *pimprove =
4725  if (pimprove) {
4726  BV_SET(pdcity->improvements, improvement_index(pimprove));
4727  }
4728  }
4729  }
4730 
4731  // Use the section as backup name.
4732  sz_strlcpy(pdcity->name, secfile_lookup_str_default(loading->file, citystr,
4733  "%s.name", citystr));
4734 
4735  pdcity->occupied = secfile_lookup_bool_default(loading->file, false,
4736  "%s.occupied", citystr);
4737  pdcity->walls =
4738  secfile_lookup_bool_default(loading->file, false, "%s.walls", citystr);
4739  pdcity->happy =
4740  secfile_lookup_bool_default(loading->file, false, "%s.happy", citystr);
4741  pdcity->unhappy = secfile_lookup_bool_default(loading->file, false,
4742  "%s.unhappy", citystr);
4743  stylename = secfile_lookup_str_default(loading->file, nullptr, "%s.style",
4744  citystr);
4745  if (stylename != nullptr) {
4746  pdcity->style = city_style_by_rule_name(stylename);
4747  } else {
4748  pdcity->style = 0;
4749  }
4750  if (pdcity->style < 0) {
4751  pdcity->style = 0;
4752  }
4753 
4754  pdcity->city_image = secfile_lookup_int_default(loading->file, -100,
4755  "%s.city_image", citystr);
4756 
4757  pdcity->capital = CAPITAL_NOT;
4758 
4759  return true;
4760 }
4761 
4762 /* =======================================================================
4763  * Load the researches.
4764  * ======================================================================= */
4765 
4769 static void sg_load_researches(struct loaddata *loading)
4770 {
4771  struct research *presearch;
4772  int count;
4773  int number;
4774  const char *string;
4775  int i, j;
4776 
4777  // Check status and return if not OK (sg_success != TRUE).
4778  sg_check_ret();
4779 
4780  // Initialize all researches.
4781  for (auto &pinitres : research_array) {
4782  if (research_is_valid(pinitres)) {
4783  init_tech(&pinitres, false);
4784  }
4785  };
4786 
4787  // May be unsaved (e.g. scenario case).
4788  count = secfile_lookup_int_default(loading->file, 0, "research.count");
4789  for (i = 0; i < count; i++) {
4791  secfile_lookup_int(loading->file, &number, "research.r%d.number", i),
4792  "%s", secfile_error());
4793  presearch = research_by_number(number);
4794  sg_failure_ret(presearch != nullptr,
4795  "Invalid research number %d in 'research.r%d.number'",
4796  number, i);
4797 
4798  presearch->tech_goal =
4799  technology_load(loading->file, "research.r%d.goal", i);
4801  &presearch->techs_researched,
4802  "research.r%d.techs", i),
4803  "%s", secfile_error());
4804  sg_failure_ret(secfile_lookup_int(loading->file, &presearch->future_tech,
4805  "research.r%d.futuretech", i),
4806  "%s", secfile_error());
4808  &presearch->bulbs_researched,
4809  "research.r%d.bulbs", i),
4810  "%s", secfile_error());
4812  &presearch->bulbs_researching_saved,
4813  "research.r%d.bulbs_before", i),
4814  "%s", secfile_error());
4815  presearch->researching_saved =
4816  technology_load(loading->file, "research.r%d.saved", i);
4817  presearch->researching =
4818  technology_load(loading->file, "research.r%d.now", i);
4819  sg_failure_ret(secfile_lookup_bool(loading->file, &presearch->got_tech,
4820  "research.r%d.got_tech", i),
4821  "%s", secfile_error());
4822 
4823  string = secfile_lookup_str(loading->file, "research.r%d.done", i);
4824  sg_failure_ret(string != nullptr, "%s", secfile_error());
4825  sg_failure_ret(strlen(string) == loading->technology.size,
4826  "Invalid length of 'research.r%d.done' (%lu ~= %lu).", i,
4827  (unsigned long) qstrlen(string),
4828  (unsigned long) loading->technology.size);
4829  for (j = 0; j < loading->technology.size; j++) {
4830  sg_failure_ret(string[j] == '1' || string[j] == '0',
4831  "Undefined value '%c' within 'research.r%d.done'.",
4832  string[j], i);
4833 
4834  if (string[j] == '1') {
4835  struct advance *padvance =
4836  advance_by_rule_name(loading->technology.order[j]);
4837 
4838  if (padvance) {
4839  research_invention_set(presearch, advance_number(padvance),
4840  TECH_KNOWN);
4841  }
4842  }
4843  }
4844  }
4845 
4846  /* In case of tech_leakage, we can update research only after all the
4847  * researches have been loaded */
4848  for (auto &pupres : research_array) {
4849  if (research_is_valid(pupres)) {
4850  research_update(&pupres);
4851  }
4852  };
4853 }
4854 
4855 /* =======================================================================
4856  * Load the event cache. Should be the last thing to do.
4857  * ======================================================================= */
4858 
4862 static void sg_load_event_cache(struct loaddata *loading)
4863 {
4864  // Check status and return if not OK (sg_success != TRUE).
4865  sg_check_ret();
4866 
4867  event_cache_load(loading->file, "event_cache");
4868 }
4869 
4870 /* =======================================================================
4871  * Load the open treaties
4872  * ======================================================================= */
4873 
4877 static void sg_load_treaties(struct loaddata *loading)
4878 {
4879  int tidx;
4880  const char *plr0;
4881  struct treaty_list *treaties = get_all_treaties();
4882 
4883  // Check status and return if not OK (sg_success != TRUE).
4884  sg_check_ret();
4885 
4886  for (tidx = 0; (plr0 = secfile_lookup_str_default(loading->file, nullptr,
4887  "treaty%d.plr0", tidx))
4888  != nullptr;
4889  tidx++) {
4890  const char *plr1;
4891  const char *ct;
4892  int cidx;
4893  struct player *p0, *p1;
4894 
4895  plr1 = secfile_lookup_str(loading->file, "treaty%d.plr1", tidx);
4896 
4897  p0 = player_by_name(plr0);
4898  p1 = player_by_name(plr1);
4899 
4900  if (p0 == nullptr || p1 == nullptr) {
4901  qCritical("Treaty between unknown players %s and %s", plr0, plr1);
4902  } else {
4903  struct Treaty *ptreaty = new Treaty;
4904 
4905  init_treaty(ptreaty, p0, p1);
4906  treaty_list_prepend(treaties, ptreaty);
4907 
4908  for (cidx = 0; (ct = secfile_lookup_str_default(
4909  loading->file, nullptr, "treaty%d.clause%d.type",
4910  tidx, cidx))
4911  != nullptr;
4912  cidx++) {
4913  enum clause_type type = clause_type_by_name(ct, fc_strcasecmp);
4914  const char *plrx;
4915 
4916  if (!clause_type_is_valid(type)) {
4917  qCritical("Invalid clause type \"%s\"", ct);
4918  } else {
4919  struct player *pgiver = nullptr;
4920 
4921  plrx = secfile_lookup_str(loading->file, "treaty%d.clause%d.from",
4922  tidx, cidx);
4923 
4924  if (!fc_strcasecmp(plrx, plr0)) {
4925  pgiver = p0;
4926  } else if (!fc_strcasecmp(plrx, plr1)) {
4927  pgiver = p1;
4928  } else {
4929  qCritical("Clause giver %s is not participant of the treaty"
4930  "between %s and %s",
4931  plrx, plr0, plr1);
4932  }
4933 
4934  if (pgiver != nullptr) {
4935  int value;
4936 
4938  loading->file, 0, "treaty%d.clause%d.value", tidx, cidx);
4939 
4940  add_clause(ptreaty, pgiver, type, value);
4941  }
4942  }
4943 
4944  /* These must be after clauses have been added so that acceptance
4945  * does not get cleared by what seems like changes to the treaty. */
4947  loading->file, false, "treaty%d.accept0", tidx);
4949  loading->file, false, "treaty%d.accept1", tidx);
4950  }
4951  }
4952  }
4953 }
4954 
4955 /* =======================================================================
4956  * Load the history report
4957  * ======================================================================= */
4958 
4962 static void sg_load_history(struct loaddata *loading)
4963 {
4964  struct history_report *hist = history_report_get();
4965  int turn;
4966 
4967  // Check status and return if not OK (sg_success != TRUE).
4968  sg_check_ret();
4969 
4970  turn = secfile_lookup_int_default(loading->file, -2, "history.turn");
4971 
4972  if (turn + 1 >= game.info.turn) {
4973  const char *str;
4974 
4975  hist->turn = turn;
4976  str = secfile_lookup_str(loading->file, "history.title");
4977  sg_failure_ret(str != nullptr, "%s", secfile_error());
4978  sz_strlcpy(hist->title, str);
4979  str = secfile_lookup_str(loading->file, "history.body");
4980  sg_failure_ret(str != nullptr, "%s", secfile_error());
4981  sz_strlcpy(hist->body, str);
4982  }
4983 }
4984 
4985 /* =======================================================================
4986  * Load the mapimg definitions.
4987  * ======================================================================= */
4988 
4992 static void sg_load_mapimg(struct loaddata *loading)
4993 {
4994  int mapdef_count, i;
4995 
4996  // Check status and return if not OK (sg_success != TRUE).
4997  sg_check_ret();
4998 
4999  // Clear all defined map images.
5000  while (mapimg_count() > 0) {
5001  mapimg_delete(0);
5002  }
5003 
5004  mapdef_count =
5005  secfile_lookup_int_default(loading->file, 0, "mapimg.count");
5006  qDebug("Saved map image definitions: %d.", mapdef_count);
5007 
5008  if (0 >= mapdef_count) {
5009  return;
5010  }
5011 
5012  for (i = 0; i < mapdef_count; i++) {
5013  const char *p;
5014 
5015  p = secfile_lookup_str(loading->file, "mapimg.mapdef%d", i);
5016  if (nullptr == p) {
5017  qDebug("[Mapimg %4d] Missing definition.", i);
5018  continue;
5019  }
5020 
5021  if (!mapimg_define(p, false)) {
5022  qCritical("Invalid map image definition %4d: %s.", i, p);
5023  }
5024 
5025  qDebug("Mapimg %4d loaded.", i);
5026  }
5027 }
5028 
5029 /* =======================================================================
5030  * Sanity checks for loading a game.
5031  * ======================================================================= */
5032 
5036 static void sg_load_sanitycheck(struct loaddata *loading)
5037 {
5038  int players;
5039 
5040  // Check status and return if not OK (sg_success != TRUE).
5041  sg_check_ret();
5042 
5043  if (game.info.is_new_game) {
5044  // Nothing to do for new games (or not started scenarios).
5045  return;
5046  }
5047 
5048  /* Old savegames may have maxplayers lower than current player count,
5049  * fix. */
5050  players = normal_player_count();
5051  if (game.server.max_players < players) {
5052  qDebug("Max players lower than current players, fixing");
5053  game.server.max_players = players;
5054  }
5055 
5056  // Fix ferrying sanity
5057  players_iterate(pplayer)
5058  {
5059  unit_list_iterate_safe(pplayer->units, punit)
5060  {
5061  if (!unit_transport_get(punit)
5062  && !can_unit_exist_at_tile(&(wld.map), punit, unit_tile(punit))) {
5063  log_sg("Removing %s unferried %s in %s at (%d, %d)",
5065  unit_rule_name(punit),
5067  TILE_XY(unit_tile(punit)));
5068  bounce_unit(punit, true);
5069  }
5070  }
5072  }
5074 
5075  /* Fix stacking issues. We don't rely on the savegame preserving
5076  * alliance invariants (old savegames often did not) so if there are any
5077  * unallied units on the same tile we just bounce them. */
5078  players_iterate(pplayer)
5079  {
5080  players_iterate(aplayer) { resolve_unit_stacks(pplayer, aplayer, true); }
5082  }
5084 
5085  /* Recalculate the potential buildings for each city. Has caused some
5086  * problems with game random state.
5087  * This also changes the game state if you save the game directly after
5088  * loading it and compare the results. */
5089  players_iterate(pplayer)
5090  {
5091  bool saved_ai_control = is_ai(pplayer);
5092 
5093  // Recalculate for all players.
5094  set_as_human(pplayer);
5095 
5096  // Building advisor needs data phase open in order to work
5097  adv_data_phase_init(pplayer, false);
5098  building_advisor(pplayer);
5099  // Close data phase again so it can be opened again when game starts.
5100  adv_data_phase_done(pplayer);
5101 
5102  if (saved_ai_control) {
5103  set_as_ai(pplayer);
5104  }
5105  }
5107 
5108  // Check worked tiles map
5109 #ifdef FREECIV_DEBUG
5110  if (loading->worked_tiles != nullptr) {
5111  // check the entire map for unused worked tiles
5112  whole_map_iterate(&(wld.map), ptile)
5113  {
5114  if (loading->worked_tiles[ptile->index] != -1) {
5115  qCritical("[city id: %d] Unused worked tile at (%d, %d).",
5116  loading->worked_tiles[ptile->index], TILE_XY(ptile));
5117  }
5118  }
5120  }
5121 #endif // FREECIV_DEBUG
5122 
5123  // Check researching technologies and goals.
5124  for (auto &presearch : research_array) {
5125  if (research_is_valid(presearch)) {
5126  if (presearch.researching != A_UNSET
5127  && !is_future_tech(presearch.researching)
5128  && (valid_advance_by_number(presearch.researching) == nullptr
5129  || (research_invention_state(&presearch, presearch.researching)
5130  != TECH_PREREQS_KNOWN))) {
5131  log_sg(_("%s had invalid researching technology."),
5132  research_name_translation(&presearch));
5133  presearch.researching = A_UNSET;
5134  }
5135  if (presearch.tech_goal != A_UNSET
5136  && !is_future_tech(presearch.tech_goal)
5137  && (valid_advance_by_number(presearch.tech_goal) == nullptr
5138  || !research_invention_reachable(&presearch,
5139  presearch.tech_goal)
5140  || (research_invention_state(&presearch, presearch.tech_goal)
5141  == TECH_KNOWN))) {
5142  log_sg(_("%s had invalid technology goal."),
5143  research_name_translation(&presearch));
5144  presearch.tech_goal = A_UNSET;
5145  }
5146  }
5147  };
5148 
5149  players_iterate(pplayer)
5150  {
5151  unit_list_iterate_safe(pplayer->units, punit)
5152  {
5153  if (!unit_order_list_is_sane(punit->orders.length,
5154  punit->orders.list)) {
5155  log_sg("Invalid unit orders for unit %d.", punit->id);
5156  free_unit_orders(punit);
5157  }
5158  }
5160  }
5162 
5163  if (0 == qstrlen(server.game_identifier)
5164  || !is_base64url(server.game_identifier)) {
5165  // This uses fc_rand(), so random state has to be initialized before.
5166  randomize_base64url_string(server.game_identifier,
5167  sizeof(server.game_identifier));
5168  }
5169 
5170  // Check if some player has more than one of some UTYF_UNIQUE unit type
5171  players_iterate(pplayer)
5172  {
5173  int unique_count[U_LAST];
5174 
5175  memset(unique_count, 0, sizeof(unique_count));
5176 
5177  unit_list_iterate(pplayer->units, punit)
5178  {
5179  unique_count[utype_index(unit_type_get(punit))]++;
5180  }
5182 
5183  unit_type_iterate(ut)
5184  {
5185  if (unique_count[utype_index(ut)] > 1
5186  && utype_has_flag(ut, UTYF_UNIQUE)) {
5187  log_sg(_("%s has multiple units of type %s though it should be "
5188  "possible "
5189  "to have only one."),
5190  player_name(pplayer), utype_name_translation(ut));
5191  }
5192  }
5194  }
5196 
5197  /* Restore game random state, just in case various initialization code
5198  * inexplicably altered the previously existing state. */
5199  if (!game.info.is_new_game) {
5200  fc_rand_set_state(loading->rstate);
5201 
5202  if (loading->version < 30) {
5203  /* For older savegames we have to recalculate the score with current
5204  * data, instead of using beginning-of-turn saved scores. */
5205  players_iterate(pplayer) { calc_civ_score(pplayer); }
5207  }
5208  }
5209 
5210  // At the end do the default sanity checks.
5211  sanity_check();
5212 }
struct achievement * achievement_by_rule_name(const char *name)
Returns achievement matching rule name or nullptr if there is no achievement with such name.
#define ACTION_NONE
Definition: actions.h:220
void building_advisor(struct player *pplayer)
Prime pcity->server.adv.building_want[].
bool adv_data_phase_init(struct player *pplayer, bool is_new_phase)
Make and cache lots of calculations needed for other functions.
Definition: advdata.cpp:250
void adv_data_phase_done(struct player *pplayer)
Clean up our mess.
Definition: advdata.cpp:556
const char * ai_name(const struct ai_type *ai)
Return the name of the ai type.
Definition: ai.cpp:99
#define CALL_FUNC_EACH_AI(_func,...)
Definition: ai.h:393
#define CALL_PLR_AI_FUNC(_func, _player,...)
Definition: ai.h:383
void ai_traits_init(struct player *pplayer)
Initialize ai traits for player.
Definition: aitraits.cpp:28
Base_type_id base_number(const struct base_type *pbase)
Return the base index.
Definition: base.cpp:135
struct extra_type * base_extra_get(const struct base_type *pbase)
Return extra that base is.
Definition: base.cpp:144
struct base_type * base_by_number(const Base_type_id id)
Returns base_type entry for an ID value.
Definition: base.cpp:119
struct base_type * get_base_by_gui_type(enum base_gui_type type, const struct unit *punit, const struct tile *ptile)
Get best gui_type base for given parameters.
Definition: base.cpp:175
#define BV_CLR_ALL(bv)
Definition: bitvector.h:62
#define BV_SET(bv, bit)
Definition: bitvector.h:44
#define BV_CLR(bv, bit)
Definition: bitvector.h:49
bool has_capability(const char *cap, const char *capstr)
Wrapper for fc_has_capability() for nullptr terminated strings.
Definition: capability.cpp:71
void citizens_nation_set(struct city *pcity, const struct player_slot *pslot, citizens count)
Set the number of citizens with the given nationality.
Definition: citizens.cpp:137
citizens citizens_count(const struct city *pcity)
Return the number of citizens in a city.
Definition: citizens.cpp:154
void citizens_init(struct city *pcity)
Initialise citizens data.
Definition: citizens.cpp:26
void citizens_update(struct city *pcity, struct player *plr)
void city_map_radius_sq_set(struct city *pcity, int radius_sq)
Returns the current squared radius of the city.
Definition: city.cpp:141
struct tile * city_tile(const struct city *pcity)
Return the tile location of the city.
Definition: city.cpp:1095
const char * city_name_get(const struct city *pcity)
Return the name of the city.
Definition: city.cpp:1077
int city_illness_calc(const struct city *pcity, int *ill_base, int *ill_size, int *ill_trade, int *ill_pollution)
Calculate city's illness in tenth of percent:
Definition: city.cpp:2746
void city_size_set(struct city *pcity, citizens size)
Set the city size.
Definition: city.cpp:1126
void city_add_improvement(struct city *pcity, const struct impr_type *pimprove)
Adds an improvement (and its effects) to a city.
Definition: city.cpp:3272
void destroy_city_virtual(struct city *pcity)
Removes the virtual skeleton of a city.
Definition: city.cpp:3421
struct city * create_city_virtual(struct player *pplayer, struct tile *ptile, const char *name)
Create virtual skeleton for a city.
Definition: city.cpp:3346
citizens city_size_get(const struct city *pcity)
Get the city size.
Definition: city.cpp:1101
int city_style_by_rule_name(const char *s)
Returns the city style that has the given (untranslated) rule name.
Definition: city.cpp:1633
#define cities_iterate_end
Definition: city.h:493
#define city_list_iterate(citylist, pcity)
Definition: city.h:482
#define cities_iterate(pcity)
Definition: city.h:486
#define city_tile_iterate(_radius_sq, _city_tile, _tile)
Definition: city.h:202
#define output_type_iterate(output)
Definition: city.h:764
#define MAX_CITY_SIZE
Definition: city.h:79
#define city_list_iterate_end
Definition: city.h:484
#define I_NEVER
Definition: city.h:219
#define city_tile_iterate_end
Definition: city.h:209
#define output_type_iterate_end
Definition: city.h:771
bool update_dumb_city(struct player *pplayer, struct city *pcity)
Updates a players knowledge about a city.
Definition: citytools.cpp:2637
void city_freeze_workers(struct city *pcity)
Freeze the workers (citizens on tiles) for the city.
Definition: citytools.cpp:118
bool send_city_suppression(bool now)
Suppress sending cities during game_load() and end_phase()
Definition: citytools.cpp:2127
void city_thaw_workers(struct city *pcity)
Thaw (unfreeze) the workers (citizens on tiles) for the city.
Definition: citytools.cpp:128
void reality_check_city(struct player *pplayer, struct tile *ptile)
Removes outdated (nonexistant) cities from a player.
Definition: citytools.cpp:2704
void city_refresh_vision(struct city *pcity)
Refresh the city's vision.
Definition: citytools.cpp:3261
void auto_arrange_workers(struct city *pcity)
Call sync_cities() to send the affected cities to the clients.
Definition: cityturn.cpp:359
void city_repair_size(struct city *pcity, int change)
Repair the city population without affecting city size.
Definition: cityturn.cpp:895
bool city_refresh(struct city *pcity)
Updates unit upkeeps and city internal cached data.
Definition: cityturn.cpp:147
static QString ruleset
Definition: civmanual.cpp:152
char * extras
Definition: comments.cpp:34
static void road(QVariant data1, QVariant data2)
Action "Build Road" for choice dialog.
Definition: dialogs.cpp:2374
static void base(QVariant data1, QVariant data2)
Action "Build Base" for choice dialog.
Definition: dialogs.cpp:2393
void set_ai_level_directer(struct player *pplayer, enum ai_level level)
Set an AI level and related quantities, with no feedback.
Definition: difficulty.cpp:36
static struct treaty_list * treaties
Definition: diplhand.cpp:44
struct treaty_list * get_all_treaties()
Get treaty list.
Definition: diplhand.cpp:933
bool add_clause(struct Treaty *ptreaty, struct player *pfrom, enum clause_type type, int val)
Add clause to treaty.
Definition: diptreaty.cpp:134
void init_treaty(struct Treaty *ptreaty, struct player *plr0, struct player *plr1)
Initialize treaty structure between two players.
Definition: diptreaty.cpp:87
struct extra_type * extra_type_by_rule_name(const char *name)
Returns extra type matching rule name or nullptr if there is no extra type with such name.
Definition: extras.cpp:183
struct player * extra_owner(const struct tile *ptile)
Who owns extras on tile.
Definition: extras.cpp:1013
int extra_number(const struct extra_type *pextra)
Return the extra id.
Definition: extras.cpp:132
struct extra_type * prev_extra_in_tile(const struct tile *ptile, enum extra_rmcause rmcause, const struct player *pplayer, const struct unit *punit)
Returns prev extra by cause that unit or player can remove from tile.
Definition: extras.cpp:732
const char * extra_rule_name(const struct extra_type *pextra)
Return the (untranslated) rule name of the extra type.
Definition: extras.cpp:174
struct extra_type * next_extra_for_tile(const struct tile *ptile, enum extra_cause cause, const struct player *pplayer, const struct unit *punit)
Returns next extra by cause that unit or player can build to tile.
Definition: extras.cpp:687
#define is_extra_caused_by(e, c)
Definition: extras.h:182
#define extra_index(_e_)
Definition: extras.h:163
#define EXTRA_NONE
Definition: extras.h:72
#define extra_base_get(_e_)
Definition: extras.h:170
#define extra_road_get(_e_)
Definition: extras.h:171
#define extra_type_by_cause_iterate_end
Definition: extras.h:307
#define extra_type_by_cause_iterate(_cause, _extra)
Definition: extras.h:299
#define NO_TARGET
Definition: fc_types.h:271
#define MAX_TRADE_ROUTES
Definition: fc_types.h:1073
@ ROCO_RAILROAD
Definition: fc_types.h:1067
@ ROCO_RIVER
Definition: fc_types.h:1067
@ ROCO_ROAD
Definition: fc_types.h:1067
int Tech_type_id
Definition: fc_types.h:294
unsigned char citizens
Definition: fc_types.h:305
@ RPT_POSSIBLE
Definition: fc_types.h:567
#define MAX_NUM_PLAYER_SLOTS
Definition: fc_types.h:24
int Multiplier_type_id
Definition: fc_types.h:303
enum output_type_id Output_type_id
Definition: fc_types.h:295
#define IDENTITY_NUMBER_ZERO
Definition: fc_types.h:76
#define _(String)
Definition: fcintl.h:50
struct unit * game_unit_by_number(int id)
Find unit out of all units in game: now uses fast idex method, instead of looking through all units o...
Definition: game.cpp:112
struct civ_game game
Definition: game.cpp:47
struct world wld
Definition: game.cpp:48
void initialize_globals()
Initialize wonder information.
Definition: game.cpp:640
struct city * game_city_by_number(int id)
Often used function to get a city pointer from a city ID.
Definition: game.cpp:103
#define GAME_DEFAULT_TIMEOUTINTINC
Definition: game.h:558
#define GAME_DEFAULT_SCORETURN
Definition: game.h:541
#define GAME_DEFAULT_TIMEOUTINT
Definition: game.h:557
#define GAME_DEFAULT_TIMEOUTINCMULT
Definition: game.h:560
#define GAME_DEFAULT_TIMEOUTINC
Definition: game.h:559
#define GAME_DEFAULT_RULESETDIR
Definition: game.h:630
#define GAME_DEFAULT_TIMEOUTCOUNTER
Definition: game.h:562
#define GAME_DEFAULT_PHASE_MODE
Definition: game.h:580
#define GAME_HARDCODED_DEFAULT_SKILL_LEVEL
Definition: game.h:647
struct government * government_by_rule_name(const char *name)
Returns the government that has the given (untranslated) rule name.
Definition: government.cpp:48
void idex_register_unit(struct world *iworld, struct unit *punit)
Register a unit into idex, with current punit->id.
Definition: idex.cpp:79
void idex_register_city(struct world *iworld, struct city *pcity)
Register a city into idex, with current pcity->id.
Definition: idex.cpp:61
struct impr_type * improvement_by_rule_name(const char *name)
Does a linear search of improvement_types[].name.vernacular Returns nullptr when none match.
Impr_type_id improvement_index(const struct impr_type *pimprove)
Return the improvement index.
#define WONDER_DESTROYED
Definition: improvement.h:136
#define WONDER_LOST
Definition: improvement.h:143
void adv_city_free(struct city *pcity)
Free advisors related city data.
Definition: infracache.cpp:510
void adv_city_alloc(struct city *pcity)
Allocate advisors related city data.
Definition: infracache.cpp:498
const char * name
Definition: inputfile.cpp:118
#define fc_assert_msg(condition, message,...)
Definition: log.h:96
#define fc_assert(condition)
Definition: log.h:89
#define fc_assert_ret_val(condition, val)
Definition: log.h:114
#define fc_assert_action(condition, action)
Definition: log.h:104
#define log_debug(message,...)
Definition: log.h:65
bool startpos_disallow(struct startpos *psp, struct nation_type *pnation)
Disallow the nation to start at the start position.
Definition: map.cpp:1402
#define nat_x
#define nat_y
int map_startpos_count()
Is there start positions set for map.
Definition: map.cpp:1518
struct startpos * map_startpos_new(struct tile *ptile)
Create a new start position at the given tile and return it.
Definition: map.cpp:1531
void map_init_topology()
map_init_topology needs to be called after map.topology_id is changed.
Definition: map.cpp:276
struct tile * native_pos_to_tile(const struct civ_map *nmap, int nat_x, int nat_y)
Return the tile for the given native position.
Definition: map.cpp:416
struct tile * index_to_tile(const struct civ_map *imap, int mindex)
Return the tile for the given index position.
Definition: map.cpp:429
void main_map_allocate()
Allocate main map and related global structures.
Definition: map.cpp:487
bool startpos_allow(struct startpos *psp, struct nation_type *pnation)
Allow the nation to start at the start position.
Definition: map.cpp:1385
#define MAP_INDEX_SIZE
Definition: map.h:91
#define whole_map_iterate(_map, _tile)
Definition: map.h:473
#define index_to_native_pos(pnat_x, pnat_y, mindex)
Definition: map.h:111
#define whole_map_iterate_end
Definition: map.h:480
@ MAPGEN_SCENARIO
Definition: map_types.h:43
void assign_continent_numbers()
Assigns continent and ocean numbers to all tiles, and set map.num_continents and map....
void player_map_init(struct player *pplayer)
Allocate space for map, and initialise the tiles.
Definition: maphand.cpp:1177
void update_player_tile_last_seen(struct player *pplayer, struct tile *ptile)
Remember that tile was last seen this year.
Definition: maphand.cpp:1427
void map_calculate_borders()
Update borders for all sources.
Definition: maphand.cpp:2244
void map_claim_ownership(struct tile *ptile, struct player *powner, struct tile *psource, bool claim_bases)
Claim ownership of a single tile.
Definition: maphand.cpp:2070
bool map_is_known(const struct tile *ptile, const struct player *pplayer)
Return whether the player knows the tile.
Definition: maphand.cpp:884
bool send_tile_suppression(bool now)
Suppress send_tile_info() during game_load()
Definition: maphand.cpp:469
void map_know_and_see_all(struct player *pplayer)
Call this function to unfog all tiles.
Definition: maphand.cpp:1151
bool update_player_tile_knowledge(struct player *pplayer, struct tile *ptile)
Give pplayer the correct knowledge about tile; return TRUE iff knowledge changed.
Definition: maphand.cpp:1357
void tile_claim_bases(struct tile *ptile, struct player *powner)
Claim ownership of bases on single tile.
Definition: maphand.cpp:2083
void map_set_known(struct tile *ptile, struct player *pplayer)
Set known status of the tile.
Definition: maphand.cpp:1133
bool map_is_known_and_seen(const struct tile *ptile, const struct player *pplayer, enum vision_layer vlayer)
Returns whether the layer 'vlayer' of the tile 'ptile' is known and seen by the player 'pplayer'.
Definition: maphand.cpp:894
void change_playertile_site(struct player_tile *ptile, struct vision_site *new_site)
Changes site information for player tile.
Definition: maphand.cpp:1122
void give_shared_vision(struct player *pfrom, struct player *pto)
Starts shared vision between two players.
Definition: maphand.cpp:1568
struct player_tile * map_get_player_tile(const struct tile *ptile, const struct player *pplayer)
Players' information of tiles is tracked so that fogged area can be kept consistent even when the cli...
Definition: maphand.cpp:1341
int mapimg_count()
Return the number of map image definitions.
Definition: mapimg.cpp:420
bool mapimg_define(const char *maparg, bool check)
Define on map image.
Definition: mapimg.cpp:590
bool mapimg_delete(int id)
Delete a map image definition.
Definition: mapimg.cpp:918
void set_meta_patches_string(const char *string)
Set the metaserver patches string.
Definition: meta.cpp:132
const char * default_meta_patches_string()
The default metaserver patches for this server.
Definition: meta.cpp:58
#define DEFAULT_META_SERVER_ADDR
Definition: meta.h:21
bool can_unit_exist_at_tile(const struct civ_map *nmap, const struct unit *punit, const struct tile *ptile)
Return TRUE iff the unit can "exist" at this location.
Definition: movement.cpp:267
const char * multiplier_rule_name(const struct multiplier *pmul)
Return the (untranslated) rule name of the multiplier.
struct multiplier * multiplier_by_rule_name(const char *name)
Returns multiplier matching rule name, or nullptr if there is no multiplier with such a name.
Multiplier_type_id multiplier_index(const struct multiplier *pmul)
Returns multiplier index.
Definition: multipliers.cpp:77
#define multipliers_iterate(_mul_)
Definition: multipliers.h:45
#define multipliers_iterate_end
Definition: multipliers.h:51
const char * nation_rule_name(const struct nation_type *pnation)
Return the (untranslated) rule name of the nation (adjective form).
Definition: nation.cpp:115
const char * nation_plural_for_player(const struct player *pplayer)
Return the (translated) plural noun of the given nation of a player.
Definition: nation.cpp:155
struct nation_type * nation_by_rule_name(const char *name)
Returns the nation that has the given (untranslated) rule name (adjective).
Definition: nation.cpp:98
struct nation_type * nation_of_player(const struct player *pplayer)
Return the nation of a player.
Definition: nation.cpp:419
#define NO_NATION_SELECTED
Definition: nation.h:21
void event_cache_load(struct section_file *file, const char *section)
Load the event cache from a savefile.
Definition: notify.cpp:772
int parts
Definition: packhand.cpp:132
char * lines
Definition: packhand.cpp:131
int len
Definition: packhand.cpp:127
struct unit * player_unit_by_number(const struct player *pplayer, int unit_id)
If the specified player owns the unit with the specified id, return pointer to the unit struct.
Definition: player.cpp:1139
struct player_slot * player_slot_by_number(int player_id)
Return the possibly unused and uninitialized player slot.
Definition: player.cpp:410
bool player_slot_is_used(const struct player_slot *pslot)
Returns TRUE is this slot is "used" i.e.
Definition: player.cpp:395
struct player * player_by_name(const char *name)
Find player by given name.
Definition: player.cpp:800
struct player * player_by_number(const int player_id)
Return struct player pointer for the given player index.
Definition: player.cpp:768
int player_number(const struct player *pplayer)
Return the player index/number/id.
Definition: player.cpp:756
enum dipl_reason pplayer_can_make_treaty(const struct player *p1, const struct player *p2, enum diplstate_type treaty)
Returns true iff p1 can make given treaty with p2.
Definition: player.cpp:150
int player_count()
Return the number of players.
Definition: player.cpp:739
bool pplayers_at_war(const struct player *pplayer, const struct player *pplayer2)
Returns true iff players can attack each other.
Definition: player.cpp:1317
int player_slot_index(const struct player_slot *pslot)
Returns the index of the player slot.
Definition: player.cpp:373
int player_slot_max_used_number()
Return the highest used player slot index.
Definition: player.cpp:423
int player_index(const struct player *pplayer)
Return the player index.
Definition: player.cpp:748
struct city * player_city_by_number(const struct player *pplayer, int city_id)
If the specified player owns the city with the specified id, return pointer to the city struct.
Definition: player.cpp:1113
bool player_set_nation(struct player *pplayer, struct nation_type *pnation)
Set the player's nation to the given nation (may be nullptr).
Definition: player.cpp:780
const char * player_name(const struct player *pplayer)
Return the leader name of the player.
Definition: player.cpp:816
bool pplayers_allied(const struct player *pplayer, const struct player *pplayer2)
Returns true iff players are allied.
Definition: player.cpp:1334
struct player_diplstate * player_diplstate_get(const struct player *plr1, const struct player *plr2)
Returns diplomatic state type between two players.
Definition: player.cpp:288
#define players_iterate_end
Definition: player.h:520
dipl_reason
Definition: player.h:183
@ DIPL_ALLIANCE_PROBLEM_THEM
Definition: player.h:188
@ DIPL_ALLIANCE_PROBLEM_US
Definition: player.h:187
#define players_iterate(_pplayer)
Definition: player.h:514
#define MAX_ATTRIBUTE_BLOCK
Definition: player.h:219
#define player_list_iterate(playerlist, pplayer)
Definition: player.h:541
static bool is_barbarian(const struct player *pplayer)
Definition: player.h:474
#define player_slots_iterate(_pslot)
Definition: player.h:505
#define is_ai(plr)
Definition: player.h:227
#define player_list_iterate_end
Definition: player.h:543
#define set_as_human(plr)
Definition: player.h:228
#define players_iterate_alive_end
Definition: player.h:532
#define player_slots_iterate_end
Definition: player.h:509
#define set_as_ai(plr)
Definition: player.h:229
#define players_iterate_alive(_pplayer)
Definition: player.h:526
void server_player_set_name(struct player *pplayer, const char *name)
Try to set the player name to 'name'.
Definition: plrhand.cpp:2159
struct player * server_create_player(int player_id, const char *ai_tname, struct rgbcolor *prgbcolor, bool allow_ai_type_fallbacking)
Creates a new, uninitialized, used player slot.
Definition: plrhand.cpp:1776
void assign_player_colors()
Permanently assign colors to any players that don't already have them.
Definition: plrhand.cpp:1608
void set_shuffled_players(int *shuffled_players)
Initialize the shuffled players list (as from a loaded savegame).
Definition: plrhand.cpp:2327
void player_delegation_set(struct player *pplayer, const char *username)
Define a delegation.
Definition: plrhand.cpp:3183
void fit_nationset_to_players()
Try to select a nation set that fits the current players' nations, or failing that,...
Definition: plrhand.cpp:2588
struct nation_type * pick_a_nation(const struct nation_list *choices, bool ignore_conflicts, bool needs_startpos, enum barbarian_type barb_type)
This function returns a random-ish nation that is suitable for 'barb_type' and is usable (not already...
Definition: plrhand.cpp:2377
void server_remove_player(struct player *pplayer)
This function does not close any connections attached to this player.
Definition: plrhand.cpp:1825
void server_player_init(struct player *pplayer, bool initmap, bool needs_team)
Initialize ANY newly-created player on the server.
Definition: plrhand.cpp:1494
int normal_player_count()
Return the number of non-barbarian players.
Definition: plrhand.cpp:3140
void shuffle_players()
Shuffle or reshuffle the player order, storing in static variables above.
Definition: plrhand.cpp:2302
std::mt19937 & fc_rand_state()
Returns a reference to the current random generator state; eg for save/restore.
Definition: rand.cpp:123
void fc_rand_set_state(const std::mt19937 &state)
Replace current rand_state with user-supplied; eg for save/restore.
Definition: rand.cpp:129
void fc_rand_seed(std::mt19937 &gen)
Seeds the given generator with a random value.
Definition: rand.cpp:113
const char * secfile_error()
Returns the last error which occurred in a string.
bool secfile_lookup_int(const struct section_file *secfile, int *ival, const char *path,...)
Lookup a integer value in the secfile.
struct entry * secfile_entry_lookup(const struct section_file *secfile, const char *path,...)
Returns the entry at "fullpath" or nullptr if not matched.
const char * secfile_lookup_str(const struct section_file *secfile, const char *path,...)
Lookup a string value in the secfile.
const char ** secfile_lookup_str_vec(const struct section_file *secfile, size_t *dim, const char *path,...)
Lookup a string vector in the secfile.
bool secfile_lookup_bool_default(const struct section_file *secfile, bool def, const char *path,...)
Lookup a boolean value in the secfile.
const char * secfile_lookup_str_default(const struct section_file *secfile, const char *def, const char *path,...)
Lookup a string value in the secfile.
struct entry * secfile_entry_by_path(const struct section_file *secfile, const char *path)
Returns the entry by the name or nullptr if not matched.
int secfile_lookup_int_default(const struct section_file *secfile, int def, const char *path,...)
Lookup a integer value in the secfile.
struct section * secfile_section_lookup(const struct section_file *secfile, const char *path,...)
Find a section by path.
bool secfile_lookup_bool(const struct section_file *secfile, bool *bval, const char *path,...)
Lookup a boolean value in the secfile.
#define secfile_lookup_enum_default(secfile, defval, specenum_type, path, ...)
Definition: registry_ini.h:448
struct history_report * history_report_get()
Return current history report.
Definition: report.cpp:1877
bool are_reqs_active(const struct player *target_player, const struct player *other_player, const struct city *target_city, const struct impr_type *target_building, const struct tile *target_tile, const struct unit *target_unit, const struct unit_type *target_unittype, const struct output_type *target_output, const struct specialist *target_specialist, const struct action *target_action, const struct requirement_vector *reqs, const enum req_problem_type prob_type, const enum vision_layer vision_layer, const enum national_intelligence nintel)
Checks the requirement(s) to see if they are active on the given target.
struct universal universal_by_rule_name(const char *kind, const char *value)
Parse requirement type (kind) and value strings into a universal structure.
bool research_invention_reachable(const struct research *presearch, const Tech_type_id tech)
Returns TRUE iff the given tech is ever reachable via research by the players sharing the research by...
Definition: research.cpp:659
enum tech_state research_invention_set(struct research *presearch, Tech_type_id tech, enum tech_state value)
Set research knowledge about tech to given state.
Definition: research.cpp:627
const char * research_name_translation(const struct research *presearch)
Returns the name of the research owner: a player name or a team name.
Definition: research.cpp:150
enum tech_state research_invention_state(const struct research *presearch, Tech_type_id tech)
Returns state of the tech for current research.
Definition: research.cpp:609
struct research * research_by_number(int number)
Returns the research for the given index.
Definition: research.cpp:100
bool research_is_valid(const struct research &presearch)
Checks whether the research object is valid in the current game.
Definition: research.cpp:125
void research_update(struct research *presearch)
Mark as TECH_PREREQS_KNOWN each tech which is available, not known and which has all requirements ful...
Definition: research.cpp:486
std::vector< research > research_array
void rgbcolor_destroy(struct rgbcolor *prgbcolor)
Free rgbcolor structure.
Definition: rgbcolor.cpp:65
bool rgbcolor_load(struct section_file *file, struct rgbcolor **prgbcolor, const char *path,...)
Lookup an RGB color definition ([colorpath].red, [colorpath].green and [colorpath]....
Definition: rgbcolor.cpp:78
Road_type_id road_number(const struct road_type *proad)
Return the road id.
Definition: road.cpp:23
struct road_type * road_by_compat_special(enum road_compat compat)
Return road type represented by given compatibility special, or nullptr if special does not represent...
Definition: road.cpp:152
struct road_type * road_by_number(Road_type_id id)
Return road type of given id.
Definition: road.cpp:46
struct extra_type * road_extra_get(const struct road_type *proad)
Return extra that road is.
Definition: road.cpp:33
bool load_rulesets(const char *restore, const char *alt, bool compat_mode, rs_conversion_logger logger, bool act, bool buffer_script, bool load_luadata)
Loads the rulesets.
Definition: ruleset.cpp:8582
#define sanity_check()
Definition: sanitycheck.h:37
#define sanity_check_city(x)
Definition: sanitycheck.h:35
struct extra_type * resource_by_identifier(const char identifier)
Return the resource type matching the identifier, or nullptr when none matches.
Definition: savecompat.cpp:321
int sg_order_to_action(int order, struct unit *act_unit, struct tile *tgt_tile)
Returns the action id corresponding to the specified order id.
const char * special_rule_name(enum tile_special_type type)
Return the untranslated name of the given special.
Definition: savecompat.cpp:295
void set_unit_activity_road(struct unit *punit, Road_type_id road)
Assign a new road building task to unit.
struct extra_type * special_extra_get(int spe)
Get extra of the given special.
Definition: savecompat.cpp:305
int char2num(char ch)
Converts single character into numerical value.
Definition: savecompat.cpp:264
void sg_load_compat(struct loaddata *loading, enum sgf_version format_class)
Compatibility functions for loaded game.
Definition: savecompat.cpp:140
enum ai_level ai_level_convert(int old_level)
Translate savegame secfile data from earlier development version format to current one.
void set_unit_activity_base(struct unit *punit, Base_type_id base)
Assign a new base building task to unit.
int ascii_hex2bin(char ch, int halfbyte)
This returns a binary integer value of the ascii hex char, offset by the given number of half-bytes.
Definition: savecompat.cpp:239
enum tile_special_type special_by_rule_name(const char *name)
Return the special with the given name, or S_LAST.
Definition: savecompat.cpp:279
void sg_load_post_load_compat(struct loaddata *loading, enum sgf_version format_class)
Compatibility functions for loaded game that needs game state.
Definition: savecompat.cpp:191
#define sg_check_ret(...)
Definition: savecompat.h:134
#define sg_warn(condition, message,...)
Definition: savecompat.h:143
tile_special_type
Definition: savecompat.h:28
@ S_MINE
Definition: savecompat.h:30
@ S_HUT
Definition: savecompat.h:32
@ S_FALLOUT
Definition: savecompat.h:34
@ S_POLLUTION
Definition: savecompat.h:31
@ S_OLD_RIVER
Definition: savecompat.h:40
@ S_FARMLAND
Definition: savecompat.h:33
@ S_OLD_ROAD
Definition: savecompat.h:38
@ S_LAST
Definition: savecompat.h:37
@ S_IRRIGATION
Definition: savecompat.h:29
@ S_OLD_RAILROAD
Definition: savecompat.h:39
#define hex_chars
Definition: savecompat.h:176
#define sg_failure_ret_val(condition, _val, message,...)
Definition: savecompat.h:164
#define sg_failure_ret(condition, message,...)
Definition: savecompat.h:158
#define ORDER_OLD_BUILD_WONDER
Definition: savecompat.h:197
@ SAVEGAME_2
Definition: savecompat.h:26
#define ORDER_OLD_BUILD_CITY
Definition: savecompat.h:195
#define ORDER_OLD_DISBAND
Definition: savecompat.h:196
#define log_sg
Definition: savecompat.h:132
#define ORDER_OLD_HOMECITY
Definition: savecompat.h:199
#define sg_warn_ret_val(condition, _val, message,...)
Definition: savecompat.h:152
#define ORDER_OLD_TRADE_ROUTE
Definition: savecompat.h:198
static void sg_load_players_basic(struct loaddata *loading)
Load '[player]' (basic data).
Definition: savegame2.cpp:2307
static struct loaddata * loaddata_new(struct section_file *file)
Create new loaddata item for given section file.
Definition: savegame2.cpp:446
static void sg_load_map_known(struct loaddata *loading)
Load tile known status.
Definition: savegame2.cpp:2237
#define halfbyte_iterate_roads_end
Definition: savegame2.cpp:272
static struct extra_type * char2resource(char c)
Return the resource for the given identifier.
Definition: savegame2.cpp:986
static void sg_load_map_owner(struct loaddata *loading)
Load tile owner information.
Definition: savegame2.cpp:2105
static void sg_extras_set(bv_extras *extras, char ch, struct extra_type **idx)
Helper function for loading extras from a savegame.
Definition: savegame2.cpp:754
bool sg_success
Definition: savecompat.cpp:30
static void sg_bases_set(bv_extras *extras, char ch, struct base_type **idx)
Helper function for loading bases from a savegame.
Definition: savegame2.cpp:928
#define halfbyte_iterate_extras_end
Definition: savegame2.cpp:242
static void sg_load_map_tiles_roads(struct loaddata *loading)
Load roads to map.
Definition: savegame2.cpp:1935
#define halfbyte_iterate_extras(e, num_extras_types)
Definition: savegame2.cpp:237
static void sg_load_map(struct loaddata *loading)
Load '[map'].
Definition: savegame2.cpp:1777
static enum unit_orders char2order(char order)
Returns an order for a character identifier.
Definition: savegame2.cpp:510
static int unquote_block(const char *const quoted_, void *dest, int dest_length)
Unquote a string.
Definition: savegame2.cpp:656
#define LOAD_MAP_CHAR(ch, ptile, SET_XY_CHAR, secfile, secpath,...)
Definition: savegame2.cpp:200
static void sg_load_player_city_citizens(struct loaddata *loading, struct player *plr, struct city *pcity, const char *citystr)
Load nationality data for one city.
Definition: savegame2.cpp:3607
static void sg_load_player_cities(struct loaddata *loading, struct player *plr)
Load city data.
Definition: savegame2.cpp:3231
static void sg_load_map_tiles(struct loaddata *loading)
Load tiles of the map.
Definition: savegame2.cpp:1855
static char activity2char(enum unit_activity activity)
Returns a character identifier for an activity.
Definition: savegame2.cpp:578
static void sg_load_savefile(struct loaddata *loading)
Load '[savefile]'.
Definition: savegame2.cpp:1096
static enum unit_activity char2activity(char activity)
Returns an activity for a character identifier.
Definition: savegame2.cpp:635
static bool sg_load_player_unit(struct loaddata *loading, struct player *plr, struct unit *punit, const char *unitstr)
Load one unit.
Definition: savegame2.cpp:3729
static void sg_load_settings(struct loaddata *loading)
Load '[settings]'.
Definition: savegame2.cpp:1757
static void sg_load_player_units(struct loaddata *loading, struct player *plr)
Load unit data.
Definition: savegame2.cpp:3657
#define halfbyte_iterate_special(s, num_specials_types)
Definition: savegame2.cpp:247
void savegame2_load(struct section_file *file)
Really loading the savegame.
Definition: savegame2.cpp:377
static void sg_load_researches(struct loaddata *loading)
Load '[research]'.
Definition: savegame2.cpp:4769
#define halfbyte_iterate_bases_end
Definition: savegame2.cpp:262
static void sg_load_map_worked(struct loaddata *loading)
Load worked tiles information.
Definition: savegame2.cpp:2193
static void sg_load_random(struct loaddata *loading)
Load '[random]'.
Definition: savegame2.cpp:1594
#define halfbyte_iterate_special_end
Definition: savegame2.cpp:252
#define halfbyte_iterate_bases(b, num_bases_types)
Definition: savegame2.cpp:257
static void sg_load_player_units_transport(struct loaddata *loading, struct player *plr)
Load the transport status of all units.
Definition: savegame2.cpp:4321
static void sg_load_history(struct loaddata *loading)
Load '[history]'.
Definition: savegame2.cpp:4962
static void sg_load_map_tiles_specials(struct loaddata *loading, bool rivers_overlay)
Load information about specials on map.
Definition: savegame2.cpp:1954
#define TOKEN_SIZE
Definition: savegame2.cpp:276
static void sg_load_script(struct loaddata *loading)
Load '[script]'.
Definition: savegame2.cpp:1652
static void sg_load_scenario(struct loaddata *loading)
Load '[scenario]'.
Definition: savegame2.cpp:1667
static void sg_load_ruleset(struct loaddata *loading)
Set up correct ruleset for the savegame.
Definition: savegame2.cpp:1061
static void sg_load_game(struct loaddata *loading)
Load '[game]'.
Definition: savegame2.cpp:1450
static void sg_load_player_main(struct loaddata *loading, struct player *plr)
Main player data loading function.
Definition: savegame2.cpp:2760
static void sg_load_treaties(struct loaddata *loading)
Load '[treaty_xxx]'.
Definition: savegame2.cpp:4877
static void sg_roads_set(bv_extras *extras, char ch, struct road_type **idx)
Helper function for loading roads from a savegame.
Definition: savegame2.cpp:959
static Tech_type_id technology_load(struct section_file *file, const char *path, int plrno)
Load technology from path_name and if doesn't exist (because savegame is too old) load from path.
Definition: savegame2.cpp:1022
static void unit_ordering_apply()
For each city and tile, sort unit lists according to ord_city and ord_map values.
Definition: savegame2.cpp:728
static enum direction8 char2dir(char dir)
Returns a direction for a character identifier.
Definition: savegame2.cpp:549
static bool sg_load_player_city(struct loaddata *loading, struct player *plr, struct city *pcity, const char *citystr)
Load data for one city.
Definition: savegame2.cpp:3346
static void sg_load_map_tiles_resources(struct loaddata *loading)
Load information about resources on map.
Definition: savegame2.cpp:1988
static struct terrain * char2terrain(char ch)
Dereferences the terrain character.
Definition: savegame2.cpp:1000
static void sg_load_mapimg(struct loaddata *loading)
Load '[mapimg]'.
Definition: savegame2.cpp:4992
static void sg_load_player_attributes(struct loaddata *loading, struct player *plr)
Load player (client) attributes data.
Definition: savegame2.cpp:4369
static void sg_load_ruledata(struct loaddata *loading)
Load '[ruledata]'.
Definition: savegame2.cpp:1427
static void worklist_load(struct section_file *file, struct worklist *pwl, const char *path,...)
Load the worklist elements specified by path to the worklist pointed to by 'pwl'.
Definition: savegame2.cpp:688
static void sg_load_player_vision(struct loaddata *loading, struct player *plr)
Load vision data.
Definition: savegame2.cpp:4437
static bool sg_load_player_vision_city(struct loaddata *loading, struct player *plr, struct vision_site *pdcity, const char *citystr)
Load data for one seen city.
Definition: savegame2.cpp:4668
static void sg_load_map_startpos(struct loaddata *loading)
Load starting positions for the players from a savegame file.
Definition: savegame2.cpp:2018
static void loaddata_destroy(struct loaddata *loading)
Free resources allocated for loaddata item.
Definition: savegame2.cpp:485
static void sg_load_players(struct loaddata *loading)
Load '[player]'.
Definition: savegame2.cpp:2571
static void sg_load_map_tiles_extras(struct loaddata *loading)
Load extras to map.
Definition: savegame2.cpp:1897
static void sg_load_sanitycheck(struct loaddata *loading)
Sanity check for loaded game.
Definition: savegame2.cpp:5036
static void sg_load_event_cache(struct loaddata *loading)
Load '[event_cache]'.
Definition: savegame2.cpp:4862
static void sg_load_map_tiles_bases(struct loaddata *loading)
Load bases to map.
Definition: savegame2.cpp:1916
static void sg_special_set(struct tile *ptile, bv_extras *extras, char ch, const enum tile_special_type *idx, bool rivers_overlay)
Complicated helper function for loading specials from a savegame.
Definition: savegame2.cpp:788
#define halfbyte_iterate_roads(r, num_roads_types)
Definition: savegame2.cpp:267
void calc_civ_score(struct player *pplayer)
Calculates the civilization score for the player.
Definition: score.cpp:255
void script_server_state_load(struct section_file *file)
Load the scripting state from file.
void settings_game_load(struct section_file *file, const char *section)
Restore all settings from a savegame.
Definition: settings.cpp:4487
struct setting_list * level[OLEVELS_NUM]
Definition: settings.cpp:167
bool str_to_int(const char *str, int *pint)
Convert 'str' to it's int reprentation if possible.
Definition: shared.cpp:384
char scanin(char **buf, char *delimiters, char *dest, int size)
Scan in a word or set of words from start to but not including any of the given delimiters.
Definition: shared.cpp:1142
bool is_base64url(const char *s)
Check for valid base64url.
Definition: shared.cpp:258
void randomize_base64url_string(char *s, size_t n)
generate a random string meeting criteria such as is_ascii_name(), is_base64url(),...
Definition: shared.cpp:279
#define CLIP(lower, current, upper)
Definition: shared.h:51
#define ARRAY_SIZE(x)
Definition: shared.h:79
void spaceship_calc_derived(struct player_spaceship *ship)
Calculate and fill in the derived quantities about the spaceship.
Definition: spacerace.cpp:37
void spaceship_init(struct player_spaceship *ship)
Initialize spaceship struct; could also be used to "cancel" a spaceship (eg, if/when capital-capture ...
Definition: spaceship.cpp:45
#define NUM_SS_STRUCTURALS
Definition: spaceship.h:84
spaceship_state
Definition: spaceship.h:77
@ SSHIP_LAUNCHED
Definition: spaceship.h:80
@ SSHIP_NONE
Definition: spaceship.h:78
struct specialist * specialist_by_rule_name(const char *name)
Return the specialist type with the given (untranslated!) rule name.
Definition: specialist.cpp:104
Specialist_type_id specialist_index(const struct specialist *sp)
Return the specialist index.
Definition: specialist.cpp:74
#define specialist_type_iterate_end
Definition: specialist.h:73
#define specialist_type_iterate(sp)
Definition: specialist.h:67
#define DEFAULT_SPECIALIST
Definition: specialist.h:37
size_t size
Definition: specvec.h:64
void server_game_init(bool keep_ruleset_value)
Initialize game data for the server (corresponds to server_game_free).
Definition: srv_main.cpp:3179
const char * aifill(int amount)
Fill or remove players to meet the given aifill.
Definition: srv_main.cpp:2440
void server_game_free()
Free game data that we reinitialize as part of a server soft restart.
Definition: srv_main.cpp:3204
void identity_number_reserve(int id)
Mark identity number allocated.
Definition: srv_main.cpp:1969
struct server_arguments srvarg
Definition: srv_main.cpp:118
void init_game_seed()
Initialize the game seed.
Definition: srv_main.cpp:147
bool game_was_started()
Returns iff the game was started once upon a time.
Definition: srv_main.cpp:251
void update_nations_with_startpos()
Update information about which nations have start positions on the map.
Definition: srv_main.cpp:2239
bool accept0
Definition: diptreaty.h:71
bool accept1
Definition: diptreaty.h:71
struct player * first
Definition: achievements.h:28
bv_player achievers
Definition: achievements.h:29
Definition: tech.h:113
Definition: base.h:43
int turn
Definition: city.h:218
Definition: city.h:291
struct worker_task_list * task_reqs
Definition: city.h:381
int turn_last_built
Definition: city.h:358
int food_stock
Definition: city.h:338
struct built_status built[B_LAST]
Definition: city.h:366
struct player * original
Definition: city.h:295
int history
Definition: city.h:379
bool did_sell
Definition: city.h:352
int id
Definition: city.h:296
int last_turns_shield_surplus
Definition: city.h:364
int disbanded_shields
Definition: city.h:363
int turn_plague
Definition: city.h:345
bv_city_options city_options
Definition: city.h:375
bool was_happy
Definition: city.h:353
int turn_founded
Definition: city.h:357
int airlift
Definition: city.h:349
int caravan_shields
Definition: city.h:362
bool did_buy
Definition: city.h:351
struct trade_route_list * routes
Definition: city.h:313
int anarchy
Definition: city.h:355
struct worklist worklist
Definition: city.h:373
struct universal production
Definition: city.h:368
citizens * nationality
Definition: city.h:310
int steal
Definition: city.h:383
char name[MAX_LEN_CITYNAME]
Definition: city.h:292
int before_change_shields
Definition: city.h:360
struct city::@15::@17 server
int style
Definition: city.h:297
citizens specialists[SP_MAX]
Definition: city.h:305
struct tile * tile
Definition: city.h:293
int shield_stock
Definition: city.h:339
struct universal changed_from
Definition: city.h:371
struct unit_list * units_supported
Definition: city.h:377
int rapture
Definition: city.h:356
struct civ_game::@28::@32 server
struct packet_scenario_description scenario_desc
Definition: game.h:79
struct packet_ruleset_control control
Definition: game.h:74
struct packet_game_info info
Definition: game.h:80
struct packet_scenario_info scenario
Definition: game.h:78
int xsize
Definition: map_types.h:73
int ysize
Definition: map_types.h:73
struct civ_map::@39::@41 server
int changed_to_times
Definition: government.h:43
char title[REPORT_TITLESIZE]
Definition: report.h:23
char body[REPORT_BODYSIZE]
Definition: report.h:24
struct loaddata::@96 trait
const char * secfile_options
Definition: savecompat.h:45
int version
Definition: savecompat.h:46
struct loaddata::@98 multiplier
struct loaddata::@97 extra
size_t size
Definition: savecompat.h:51
struct loaddata::@103 ds_t
struct loaddata::@93 improvement
enum server_states server_state
Definition: savecompat.h:123
struct loaddata::@94 technology
const char ** order
Definition: savecompat.h:50
std::mt19937 rstate
Definition: savecompat.h:126
struct loaddata::@101 road
struct loaddata::@99 special
struct loaddata::@100 base
struct loaddata::@95 activities
int * worked_tiles
Definition: savecompat.h:129
struct loaddata::@102 specialist
struct section_file * file
Definition: savecompat.h:44
enum ai_level skill_level
Definition: player.h:109
std::vector< ai_trait > traits
Definition: player.h:119
enum barbarian_type barbarian_type
Definition: player.h:115
int science_cost
Definition: player.h:112
int love[MAX_NUM_PLAYER_SLOTS]
Definition: player.h:117
int expand
Definition: player.h:111
int fuzzy
Definition: player.h:110
int has_reason_to_cancel
Definition: player.h:197
int contact_turns_left
Definition: player.h:198
int first_contact_turn
Definition: player.h:195
enum diplstate_type max_state
Definition: player.h:194
enum diplstate_type type
Definition: player.h:193
int units_killed
Definition: player.h:99
int landarea
Definition: player.h:85
int mfg
Definition: player.h:95
int population
Definition: player.h:87
int pollution
Definition: player.h:92
int wonders
Definition: player.h:81
int settledarea
Definition: player.h:86
int specialists[SP_MAX]
Definition: player.h:80
int units_lost
Definition: player.h:100
int angry
Definition: player.h:79
int techout
Definition: player.h:83
int game
Definition: player.h:103
int units
Definition: player.h:91
int units_built
Definition: player.h:98
int content
Definition: player.h:77
int happy
Definition: player.h:76
int spaceship
Definition: player.h:97
int culture
Definition: player.h:102
int unhappy
Definition: player.h:78
int cities
Definition: player.h:88
int bnp
Definition: player.h:94
int literacy
Definition: player.h:93
int techs
Definition: player.h:82
bv_spaceship_structure structure
Definition: spaceship.h:97
enum spaceship_state state
Definition: spaceship.h:105
struct player * extras_owner
Definition: maphand.h:32
struct player * owner
Definition: maphand.h:31
Definition: player.h:231
struct city_list * cities
Definition: player.h:263
QByteArray attribute_block
Definition: player.h:288
struct player_ai ai_common
Definition: player.h:270
bv_plr_flags flags
Definition: player.h:274
bool is_male
Definition: player.h:239
int wonders[B_LAST]
Definition: player.h:283
bool unassigned_ranked
Definition: player.h:237
struct government * target_government
Definition: player.h:241
char username[MAX_LEN_NAME]
Definition: player.h:234
int revolution_finishes
Definition: player.h:255
struct player::@65::@67 server
int nturns_idle
Definition: player.h:247
struct government * government
Definition: player.h:240
struct team * team
Definition: player.h:243
int turns_alive
Definition: player.h:248
struct unit_list * units
Definition: player.h:264
char ranked_username[MAX_LEN_NAME]
Definition: player.h:236
bool is_alive
Definition: player.h:250
bv_player real_embassy
Definition: player.h:259
struct player_economic economic
Definition: player.h:266
struct player_spaceship spaceship
Definition: player.h:268
struct player_score score
Definition: player.h:265
int multipliers[MAX_NUM_MULTIPLIERS]
Definition: player.h:296
struct nation_type * nation
Definition: player.h:242
struct nation_style * style
Definition: player.h:261
int multipliers_target[MAX_NUM_MULTIPLIERS]
Definition: player.h:298
bool phase_done
Definition: player.h:245
int history
Definition: player.h:300
int last_war_action
Definition: player.h:252
bool unassigned_user
Definition: player.h:235
Tech_type_id researching
Definition: research.h:45
int future_tech
Definition: research.h:35
Tech_type_id tech_goal
Definition: research.h:78
int bulbs_researching_saved
Definition: research.h:56
Tech_type_id researching_saved
Definition: research.h:55
bool got_tech
Definition: research.h:60
int techs_researched
Definition: research.h:35
int bulbs_researched
Definition: research.h:46
Definition: road.h:54
QString serverid
Definition: srv_main.h:52
QString metaserver_addr
Definition: srv_main.h:31
Definition: servers.h:55
Definition: team.cpp:35
int road_time
Definition: terrain.h:194
struct terrain * irrigation_result
Definition: terrain.h:200
struct terrain * mining_result
Definition: terrain.h:204
char identifier_load
Definition: terrain.h:178
int base_time
Definition: terrain.h:193
Definition: tile.h:42
int index
Definition: tile.h:43
bv_extras extras
Definition: tile.h:47
struct unit_list * units
Definition: tile.h:50
struct player * owner
Definition: tile.h:52
struct tile * claimer
Definition: tile.h:56
enum route_direction dir
Definition: traderoutes.h:75
struct goods_type * goods
Definition: traderoutes.h:76
enum unit_orders order
Definition: unit.h:80
Definition: unit.h:134
int length
Definition: unit.h:192
int upkeep[O_LAST]
Definition: unit.h:145
bool has_orders
Definition: unit.h:190
enum action_decision action_decision_want
Definition: unit.h:199
int battlegroup
Definition: unit.h:188
int moves_left
Definition: unit.h:147
int id
Definition: unit.h:141
bool moved
Definition: unit.h:170
int index
Definition: unit.h:192
bool vigilant
Definition: unit.h:194
int hp
Definition: unit.h:148
int fuel
Definition: unit.h:150
struct extra_type * changed_from_target
Definition: unit.h:167
enum direction8 facing
Definition: unit.h:138
struct unit::@76::@79 server
int activity_count
Definition: unit.h:159
struct unit_order * list
Definition: unit.h:195
enum unit_activity changed_from
Definition: unit.h:165
struct player * nationality
Definition: unit.h:140
bool repeat
Definition: unit.h:193
int homecity
Definition: unit.h:142
bool paradropped
Definition: unit.h:171
bool done_moving
Definition: unit.h:178
struct tile * goto_tile
Definition: unit.h:152
struct unit::@75 orders
struct tile * action_decision_tile
Definition: unit.h:200
int veteran
Definition: unit.h:149
int changed_from_count
Definition: unit.h:166
enum server_side_agent ssa_controller
Definition: unit.h:169
enum universals_n kind
Definition: fc_types.h:740
char name[MAX_LEN_NAME]
Definition: vision.h:114
bool happy
Definition: vision.h:123
bv_imprs improvements
Definition: vision.h:129
struct tile * location
Definition: vision.h:115
int identity
Definition: vision.h:118
bool walls
Definition: vision.h:122
int style
Definition: vision.h:125
bool unhappy
Definition: vision.h:124
struct player * owner
Definition: vision.h:116
int city_image
Definition: vision.h:126
bool occupied
Definition: vision.h:121
enum capital_type capital
Definition: vision.h:127
enum unit_activity act
Definition: workertask.h:17
struct tile * ptile
Definition: workertask.h:16
struct extra_type * tgt
Definition: workertask.h:18
struct universal entries[MAX_LEN_WORKLIST]
Definition: worklist.h:25
int length
Definition: worklist.h:24
struct civ_map map
Definition: world_object.h:21
int city_style(struct city *pcity)
Return citystyle of the city.
Definition: style.cpp:234
struct nation_style * style_by_rule_name(const char *name)
Returns style matching rule name or nullptr if there is no style with such name.
Definition: style.cpp:103
const char * style_rule_name(const struct nation_style *pstyle)
Return the (untranslated) rule name of the style.
Definition: style.cpp:94
struct nation_style * style_by_number(int id)
Return style of given id.
Definition: style.cpp:74
int fc_snprintf(char *str, size_t n, const char *format,...)
See also fc_utf8_snprintf_trunc(), fc_utf8_snprintf_rep().
Definition: support.cpp:537
int fc_strcasecmp(const char *str0, const char *str1)
Compare strings like strcmp(), but ignoring case.
Definition: support.cpp:89
int fc_vsnprintf(char *str, size_t n, const char *format, va_list ap)
Definition: support.cpp:512
#define sz_strlcpy(dest, src)
Definition: support.h:140
#define fc_strdup(str)
Definition: support.h:111
void team_add_player(struct player *pplayer, struct team *pteam)
Set a player to a team.
Definition: team.cpp:438
const struct player_list * team_members(const struct team *pteam)
Returns the member list of the team.
Definition: team.cpp:427
struct team * team_new(struct team_slot *tslot)
Creates a new team for the slot.
Definition: team.cpp:294
struct team_slot * team_slot_by_number(int team_id)
Return the possibly unused and uninitialized team slot.
Definition: team.cpp:157
bool is_future_tech(Tech_type_id tech)
Is the given tech a future tech.
Definition: tech.cpp:268
struct advance * advance_by_rule_name(const char *name)
Does a linear search of advances[].name.vernacular Returns nullptr when none match.
Definition: tech.cpp:180
struct advance * valid_advance_by_number(const Tech_type_id id)
Returns pointer when the advance "exists" in this game, returns nullptr otherwise.
Definition: tech.cpp:154
Tech_type_id advance_number(const struct advance *padvance)
Return the advance index.
Definition: tech.cpp:85
#define A_FUTURE
Definition: tech.h:39
#define A_NONE
Definition: tech.h:36
#define A_UNSET
Definition: tech.h:41
#define A_UNKNOWN
Definition: tech.h:42
void init_tech(struct research *research, bool update)
Initializes tech data for the research.
Definition: techtools.cpp:1075
const char * terrain_rule_name(const struct terrain *pterrain)
Return the (untranslated) rule name of the terrain.
Definition: terrain.cpp:184
struct terrain * terrain_by_rule_name(const char *name)
Return the terrain type matching the name, or T_UNKNOWN if none matches.
Definition: terrain.cpp:140
bool terrain_has_resource(const struct terrain *pterrain, const struct extra_type *presource)
Check for resource in terrain resources list.
Definition: terrain.cpp:192
#define terrain_type_iterate(_p)
Definition: terrain.h:331
#define T_UNKNOWN
Definition: terrain.h:51
#define TERRAIN_UNKNOWN_IDENTIFIER
Definition: terrain.h:181
#define terrain_type_iterate_end
Definition: terrain.h:337
#define RESOURCE_NONE_IDENTIFIER
Definition: terrain.h:41
#define RESOURCE_NULL_IDENTIFIER
Definition: terrain.h:40
bool tile_has_claimable_base(const struct tile *ptile, const struct unit_type *punittype)
Check if tile contains base providing effect for unit.
Definition: tile.cpp:203
void tile_virtual_destroy(struct tile *vtile)
Frees all memory used by the virtual tile, including freeing virtual units in the tile's unit list an...
Definition: tile.cpp:1051
bool tile_set_label(struct tile *ptile, const char *label)
Sets label for tile.
Definition: tile.cpp:1104
void tile_set_resource(struct tile *ptile, struct extra_type *presource)
Set the given resource at the specified tile.
Definition: tile.cpp:355
void tile_set_worked(struct tile *ptile, struct city *pcity)
Set the city/worker on the tile (may be nullptr).
Definition: tile.cpp:96
struct city * tile_city(const struct tile *ptile)
Return the city on this tile (or nullptr), checking for city center.
Definition: tile.cpp:72
struct tile * tile_virtual_new(const struct tile *ptile)
Returns a virtual tile.
Definition: tile.cpp:997
#define tile_index(_pt_)
Definition: tile.h:70
#define tile_worked(_tile)
Definition: tile.h:97
#define tile_terrain(_tile)
Definition: tile.h:93
#define TILE_XY(ptile)
Definition: tile.h:36
#define tile_has_extra(ptile, pextra)
Definition: tile.h:130
#define tile_owner(_tile)
Definition: tile.h:78
struct goods_type * goods_by_number(Goods_type_id id)
Return goods type of given id.
void free_unit_orders(struct unit *punit)
Free and reset the unit's goto route (punit->pgr).
Definition: unit.cpp:1633
bool unit_transport_load(struct unit *pcargo, struct unit *ptrans, bool force)
Load pcargo onto ptrans.
Definition: unit.cpp:2123
void set_unit_activity(struct unit *punit, enum unit_activity new_activity)
Assign a new untargeted task to a unit.
Definition: unit.cpp:1011
struct unit * unit_transport_get(const struct unit *pcargo)
Returns the transporter of the unit or nullptr if it is not transported.
Definition: unit.cpp:2189
bool can_unit_continue_current_activity(struct unit *punit)
Check if the unit's current activity is actually legal.
Definition: unit.cpp:780
void set_unit_activity_targeted(struct unit *punit, enum unit_activity new_activity, struct extra_type *new_target)
assign a new targeted task to a unit.
Definition: unit.cpp:1028
void unit_virtual_destroy(struct unit *punit)
Free the memory used by virtual unit.
Definition: unit.cpp:1588
struct unit * unit_virtual_create(struct player *pplayer, struct city *pcity, const struct unit_type *punittype, int veteran_level)
Create a virtual unit skeleton.
Definition: unit.cpp:1490
void unit_tile_set(struct unit *punit, struct tile *ptile)
Set the tile location of the unit.
Definition: unit.cpp:1200
#define unit_tile(_pu)
Definition: unit.h:371
#define BATTLEGROUP_NONE
Definition: unit.h:187
unit_orders
Definition: unit.h:31
@ ORDER_ACTION_MOVE
Definition: unit.h:39
@ ORDER_ACTIVITY
Definition: unit.h:35
@ ORDER_FULL_MP
Definition: unit.h:37
@ ORDER_MOVE
Definition: unit.h:33
@ ORDER_LAST
Definition: unit.h:43
@ ORDER_PERFORM_ACTION
Definition: unit.h:41
#define unit_owner(_pu)
Definition: unit.h:370
void unit_list_sort_ord_map(struct unit_list *punitlist)
Sorts the unit list by punit->server.ord_map values.
Definition: unitlist.cpp:69
void unit_list_sort_ord_city(struct unit_list *punitlist)
Sorts the unit list by punit->server.ord_city values.
Definition: unitlist.cpp:80
#define unit_list_iterate(unitlist, punit)
Definition: unitlist.h:25
#define unit_list_iterate_safe(unitlist, _unit)
Definition: unitlist.h:33
#define unit_list_iterate_end
Definition: unitlist.h:27
#define unit_list_iterate_safe_end
Definition: unitlist.h:54
void bounce_unit(struct unit *punit, bool verbose, bounce_reason reason, int max_distance)
Move or remove a unit due to stack conflicts.
Definition: unittools.cpp:1327
void resolve_unit_stacks(struct player *pplayer, struct player *aplayer, bool verbose)
When in civil war or an alliance breaks there will potentially be units from both sides coexisting on...
Definition: unittools.cpp:1537
void unit_refresh_vision(struct unit *punit)
Refresh the unit's vision.
Definition: unittools.cpp:4818
bool unit_order_list_is_sane(int length, const struct unit_order *orders)
Returns TRUE iff the unit order array is sane.
Definition: unittools.cpp:4924
const char * unit_rule_name(const struct unit *punit)
Return the (untranslated) rule name of the unit.
Definition: unittype.cpp:1283
const struct unit_type * unit_type_get(const struct unit *punit)
Return the unit type for this unit.
Definition: unittype.cpp:114
int utype_upkeep_cost(const struct unit_type *ut, struct player *pplayer, Output_type_id otype)
Returns the upkeep of a unit of this type under the given government.
Definition: unittype.cpp:123
int utype_veteran_levels(const struct unit_type *punittype)
Return veteran levels of the given unit type.
Definition: unittype.cpp:2254
const char * utype_name_translation(const struct unit_type *punittype)
Return the (translated) name of the unit type.
Definition: unittype.cpp:1256
struct unit_type * unit_type_by_rule_name(const char *name)
Returns the unit type that has the given (untranslated) rule name.
Definition: unittype.cpp:1444
Unit_type_id utype_index(const struct unit_type *punittype)
Return the unit type index.
Definition: unittype.cpp:82
static bool utype_has_flag(const struct unit_type *punittype, int flag)
Definition: unittype.h:584
#define unit_type_iterate(_p)
Definition: unittype.h:785
#define U_LAST
Definition: unittype.h:31
#define unit_type_iterate_end
Definition: unittype.h:791
struct vision * vision_new(struct player *pplayer, struct tile *ptile)
Create a new vision source.
Definition: vision.cpp:27
void vision_site_size_set(struct vision_site *psite, citizens size)
Set the city size.
Definition: vision.cpp:122
bool vision_reveal_tiles(struct vision *vision, bool reveal_tiles)
Sets the can_reveal_tiles flag.
Definition: vision.cpp:56
struct vision_site * vision_site_new(int identity, struct tile *location, struct player *owner)
Returns the basic structure.
Definition: vision.cpp:67
void worklist_init(struct worklist *pwl)
Initialize a worklist to be empty.
Definition: worklist.cpp:32