The Battle for Wesnoth  1.13.11+dev
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
game_config_manager.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2013 - 2018 by Andrius Silinskas <silinskas.andrius@gmail.com>
3  Part of the Battle for Wesnoth Project http://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 #include "game_config_manager.hpp"
15 
16 #include "about.hpp"
17 #include "addon/manager.hpp"
18 #include "ai/configuration.hpp"
19 #include "cursor.hpp"
20 #include "events.hpp"
21 #include "game_config.hpp"
22 #include "gettext.hpp"
23 #include "game_classification.hpp"
26 #include "hotkey/hotkey_item.hpp"
28 #include "language.hpp"
29 #include "log.hpp"
30 #include "preferences/general.hpp"
32 #include "terrain/builder.hpp"
33 #include "terrain/type_data.hpp"
34 #include "units/types.hpp"
35 #include "version.hpp"
36 #include "theme.hpp"
37 #include "image.hpp"
38 
39 static lg::log_domain log_config("config");
40 #define ERR_CONFIG LOG_STREAM(err, log_config)
41 #define WRN_CONFIG LOG_STREAM(warn, log_config)
42 #define LOG_CONFIG LOG_STREAM(info, log_config)
43 
45 
47  const commandline_options& cmdline_opts,
48  const bool jump_to_editor) :
49  cmdline_opts_(cmdline_opts),
50  jump_to_editor_(jump_to_editor),
51  game_config_(),
52  old_defines_map_(),
53  paths_manager_(),
54  cache_(game_config::config_cache::instance())
55 {
56  assert(!singleton);
57  singleton = this;
58 
60  cache_.set_use_cache(false);
61  }
64  }
65 }
66 
68 {
69  assert(singleton);
70  singleton = nullptr;
71 }
72 
74  return singleton;
75 }
76 
78 {
79  // Add preproc defines according to the command line arguments.
80  game_config::scoped_preproc_define multiplayer("MULTIPLAYER",
85  game_config::scoped_preproc_define title_screen("TITLE_SCREEN",
87 
90 
92 
95 
100 
101  return true;
102 }
103 
104 namespace {
105 /// returns true if every define in special is also defined in general
106 bool map_includes(const preproc_map& general, const preproc_map& special)
107 {
108  for (const preproc_map::value_type& pair : special)
109  {
110  preproc_map::const_iterator it = general.find(pair.first);
111  if (it == general.end() || it->second != pair.second) {
112  return false;
113  }
114  }
115  return true;
116 }
117 } // end anonymous namespace
118 
121 {
122  game_config::scoped_preproc_define debug_mode("DEBUG_MODE",
124 
125  // Game_config already holds requested config in memory.
126  if (!game_config_.empty()) {
127  if ((force_reload == NO_FORCE_RELOAD) && old_defines_map_ == cache_.get_preproc_map()) {
128  return;
129  }
130  if ((force_reload == NO_INCLUDE_RELOAD) && map_includes(old_defines_map_, cache_.get_preproc_map())) {
131  return;
132  }
133  }
134 
135  gui2::dialogs::loading_screen::display([this, force_reload, classification]() {
136  load_game_config(force_reload, classification);
137  });
138 }
139 
142 {
143  // Make sure that 'debug mode' symbol is set
144  // if command line parameter is selected
145  // also if we're in multiplayer and actual debug mode is disabled.
146 
147  // The loadscreen will erase the titlescreen.
148  // NOTE: even without loadscreen, needed after MP lobby.
149  try {
150  // Read all game configs.
151  // First we load all core configs, the mainline one and the ones from the addons.
152  // Validate the cores and discard the invalid.
153  // Then find the path to the selected core.
154  // Load the selected core.
155  // Handle terrains so that they are last loaded from the core.
156  // Load every compatible addon.
160 
161  // Start transaction so macros are shared.
162  game_config::config_cache_transaction main_transaction;
163 
164  config cores_cfg;
165  // Load mainline cores definition file.
166  cache_.get_config(game_config::path + "/data/cores.cfg", cores_cfg);
167 
168  // Append the $user_campaign_dir/*/cores.cfg files to the cores.
169  std::vector<std::string> user_dirs;
170  {
171  const std::string user_campaign_dir = filesystem::get_addons_dir();
172  std::vector<std::string> user_files;
173  filesystem::get_files_in_dir(user_campaign_dir, &user_files, &user_dirs,
175  }
176  for (const std::string& umc : user_dirs) {
177  const std::string cores_file = umc + "/cores.cfg";
178  if (filesystem::file_exists(cores_file)) {
179  config cores;
180  cache_.get_config(cores_file, cores);
181  cores_cfg.append(cores);
182  }
183  }
184 
185  // Validate every core
186  config valid_cores;
187  bool current_core_valid = false;
188  std::string wml_tree_root;
189  for (const config& core : cores_cfg.child_range("core")) {
190 
191  const std::string& id = core["id"];
192  if (id.empty()) {
195  _("Error validating data core."),
196  _("Found a core without id attribute.")
197  + '\n' + _("Skipping the core."));
198  });
199  continue;
200  }
201  if (*&valid_cores.find_child("core", "id", id)) {
204  _("Error validating data core."),
205  _("Core ID: ") + id
206  + '\n' + _("The ID is already in use.")
207  + '\n' + _("Skipping the core."));
208  });
209  continue;
210  }
211 
212  const std::string& path = core["path"];
216  _("Error validating data core."),
217  _("Core ID: ") + id
218  + '\n' + _("Core Path: ") + path
219  + '\n' + _("File not found.")
220  + '\n' + _("Skipping the core."));
221  });
222  continue;
223  }
224 
225  if (id == "default" && !current_core_valid) {
226  wml_tree_root = path;
227  }
228  if (id == preferences::core_id()) {
229  current_core_valid = true;
230  wml_tree_root = path;
231  }
232 
233  valid_cores.add_child("core", core); // append(core);
234  }
235 
236  if (!current_core_valid) {
239  _("Error loading core data."),
240  _("Core ID: ") + preferences::core_id()
241  + '\n' + _("Error loading the core with named id.")
242  + '\n' + _("Falling back to the default core."));
243  });
244  preferences::set_core_id("default");
245  }
246 
247  // check if we have a valid default core which should always be the case.
248  if (wml_tree_root.empty()) {
251  _("Error loading core data."),
252  _("Can't locate the default core.")
253  + '\n' + _("The game will now exit."));
254  });
255  throw;
256  }
257 
258  // Load the selected core
260  game_config_.append(valid_cores);
261 
262  main_transaction.lock();
263 
264  // Put the gfx rules aside so that we can prepend the add-on
265  // rules to them.
266  config core_terrain_rules;
267  core_terrain_rules.splice_children(game_config_, "terrain_graphics");
268 
270  load_addons_cfg();
271 
272  // If multiplayer campaign is being loaded, [scenario] tags should
273  // become [multiplayer] tags and campaign's id should be added to them
274  // to allow to recognize which scenarios belongs to a loaded campaign.
275  if (classification != nullptr) {
276  if (const config& campaign = game_config().find_child("campaign", "id", classification->campaign))
277  {
278  const bool require_campaign = campaign["require_campaign"].to_bool(true);
279  for (config& scenario : game_config_.child_range("scenario"))
280  {
281  scenario["require_scenario"] = require_campaign;
282  for (config& side : scenario.child_range("side"))
283  {
284  side["no_leader"] = side["no_leader"].to_bool(true);
285  }
286  }
287  }
288  }
289 
290  // Extract the Lua scripts at toplevel.
293 
294  // Put the gfx rules back to game config.
295  game_config_.splice_children(core_terrain_rules, "terrain_graphics");
296 
298  set_unit_data();
300 
302  tdata_ = std::make_shared<terrain_type_data>(game_config_);
305  } catch(game::error& e) {
306  ERR_CONFIG << "Error loading game configuration files\n" << e.message << '\n';
307 
308  // Try reloading without add-ons
309  if (!game_config::no_addons) {
310  game_config::no_addons = true;
313  _("Error loading custom game configuration files. The game will try without loading add-ons."),
314  e.message);
315  });
316  load_game_config(force_reload, classification);
317  } else if (preferences::core_id() != "default") {
320  _("Error loading custom game configuration files. The game will fallback to the default core files."),
321  e.message);
322  });
323  preferences::set_core_id("default");
324  game_config::no_addons = false;
325  load_game_config(force_reload, classification);
326  } else {
329  _("Error loading default core game configuration files. The game will now exit."),
330  e.message);
331  });
332  throw;
333  }
334  }
335 
337 
338  // Set new binary paths.
340 }
341 
343 {
348 };
349 
351 {
352  const std::string user_campaign_dir = filesystem::get_addons_dir();
353 
354  std::vector<std::string> error_addons;
355  std::vector<std::string> user_dirs;
356  std::vector<std::string> user_files;
357  std::vector<addon_source> addons_to_load;
358 
359  filesystem::get_files_in_dir(user_campaign_dir, &user_files, &user_dirs,
361 
362  std::vector<std::string> error_log;
363 
364  // Append the $user_campaign_dir/*.cfg files to addons_to_load.
365  for(const std::string& uc : user_files) {
366  const std::string file = uc;
367  const int size_minus_extension = file.size() - 4;
368  if(file.substr(size_minus_extension, file.size()) == ".cfg") {
369  const int userdata_loc = file.find("data/add-ons") + 5;
370  ERR_CONFIG << "error reading usermade add-on '"
371  << file << "'\n";
372  error_addons.push_back(file);
373  error_log.push_back("The format '~" + file.substr(userdata_loc)
374  + "' (for single-file add-ons) is not supported anymore, use '~"
375  + file.substr(userdata_loc,
376  size_minus_extension - userdata_loc)
377  + "/_main.cfg' instead.");
378  }
379  }
380 
381  // Rerun the directory scan using filename only, to get the addon_ids more easily.
382  user_files.clear();
383  user_dirs.clear();
384  filesystem::get_files_in_dir(user_campaign_dir, &user_files, &user_dirs,
386 
387  // Append the $user_campaign_dir/*/_main.cfg files to addons_to_load.
388  for (const std::string& uc : user_dirs) {
389  const std::string addon_id = uc;
390  const std::string addon_dir = user_campaign_dir + "/" + uc;
391 
392  const std::string main_cfg = addon_dir + "/_main.cfg";
393  const std::string info_cfg = addon_dir + "/_info.cfg";
394 
395  addon_source addon;
396  addon.main_cfg = main_cfg;
397  addon.addon_id = addon_id;
398 
399  if(filesystem::file_exists(main_cfg)) {
400  if(filesystem::file_exists(info_cfg)) {
401  config info;
402  cache_.get_config(info_cfg, info);
403 
404  const config& info_tag = info.child_or_empty("info");
405 
406  std::string core = info_tag["core"];
407  if(core.empty()) {
408  core = "default";
409  }
410 
411  addon.addon_title = info_tag["title"].str();
412 
413  // Skip add-ons not matching our current core.
414  //
415  // Don't skip:
416  // - addons which have no [info], they are most likely manually installed.
417  // - cores, we want them selectable at all times.
418  // - addons matching our current core.
419  if(!info_tag.empty() && info_tag["type"] != "core" && core != preferences::core_id()) {
420  continue;
421  }
422  }
423 
424  // Fall back to ID if no title was found (most likely in the case of missing _info.cfg).
425  // TODO: account for case where _info.cfg is missing but a .pbl file is present.
426  if(addon.addon_title.empty()) {
427  addon.addon_title = addon_id;
428  }
429 
430  // Ask the addon manager to find version info for us (from info, pbl file)
431  addon.version = get_addon_version_info(addon_id);
432  addons_to_load.push_back(addon);
433  }
434  }
435 
436  // Load the addons.
437  for (const addon_source & addon : addons_to_load) {
438  try {
439  // Load this addon from the cache, to a config
440  config umc_cfg;
441  cache_.get_config(addon.main_cfg, umc_cfg);
442 
443  // Annotate "era", "modification", and scenario tags with addon_id info
444  static const std::set<std::string> tags_with_addon_id { "era", "modification", "multiplayer", "scenario", "campaign" };
445 
446  for(auto child : umc_cfg.all_children_range()) {
447  if(tags_with_addon_id.count(child.key) > 0) {
448  auto& cfg = child.cfg;
449  cfg["addon_id"] = addon.addon_id;
450  cfg["addon_title"] = addon.addon_title;
451  // Note that this may reformat the string in a canonical form.
452  cfg["addon_version"] = addon.version.str();
453  }
454  }
455 
456  game_config_.append(umc_cfg);
457  } catch(config::error& err) {
458  ERR_CONFIG << "error reading usermade add-on '" << addon.main_cfg << "'" << std::endl;
459  ERR_CONFIG << err.message << '\n';
460  error_addons.push_back(addon.main_cfg);
461  error_log.push_back(err.message);
462  } catch(preproc_config::error& err) {
463  ERR_CONFIG << "error reading usermade add-on '" << addon.main_cfg << "'" << std::endl;
464  ERR_CONFIG << err.message << '\n';
465  error_addons.push_back(addon.main_cfg);
466  error_log.push_back(err.message);
467  } catch(filesystem::io_exception&) {
468  ERR_CONFIG << "error reading usermade add-on '" << addon.main_cfg << "'" << std::endl;
469  error_addons.push_back(addon.main_cfg);
470  }
471  }
472  if(error_addons.empty() == false) {
473  const size_t n = error_addons.size();
474  const std::string& msg1 =
475  _n("The following add-on had errors and could not be loaded:",
476  "The following add-ons had errors and could not be loaded:",
477  n);
478  const std::string& msg2 =
479  _n("Please report this to the author or maintainer of this add-on.",
480  "Please report this to the respective authors or maintainers of these add-ons.",
481  n);
482 
483  const std::string& report = utils::join(error_log, "\n\n");
485  gui2::dialogs::wml_error::display(msg1, msg2, error_addons, report);
486  });
487  }
488 }
489 
491 {
492  config& hashes = game_config_.add_child("multiplayer_hashes");
493  for (const config &ch : game_config_.child_range("multiplayer")) {
494  hashes[ch["id"].str()] = ch.hash();
495  }
496 }
497 
499 {
500  game_config_.merge_children("units");
502  if(config &units = game_config_.child("units")) {
503  unit_types.set_config(units);
504  }
505 }
506 
508 {
509  // Rebuild addon version info cache.
511 
512  // Force a reload of configuration information.
514  old_defines_map_.clear();
517 
519 }
520 
522 {
525 }
526 
529 {
530  game_config::scoped_preproc_define difficulty(classification.difficulty,
531  !classification.difficulty.empty());
532  game_config::scoped_preproc_define campaign(classification.campaign_define,
533  !classification.campaign_define.empty());
534  game_config::scoped_preproc_define scenario(classification.scenario_define,
535  !classification.scenario_define.empty());
537  !classification.era_define.empty());
538  game_config::scoped_preproc_define multiplayer("MULTIPLAYER",
539  classification.campaign_type == game_classification::CAMPAIGN_TYPE::MULTIPLAYER);
541  classification.campaign_type == game_classification::CAMPAIGN_TYPE::MULTIPLAYER);
542 
543  //
544  // NOTE: these deques aren't used here, but the objects within are utilized as RAII helpers.
545  //
546 
547  typedef std::unique_ptr<game_config::scoped_preproc_define> define;
548 
549  std::deque<define> extra_defines;
550  for(const std::string& extra_define : classification.campaign_xtra_defines) {
551  extra_defines.emplace_back(new game_config::scoped_preproc_define(extra_define));
552  }
553 
554  std::deque<define> modification_defines;
555  for(const std::string& mod_define : classification.mod_defines) {
556  modification_defines.emplace_back(new game_config::scoped_preproc_define(mod_define, !mod_define.empty()));
557  }
558 
559  try {
561  } catch(game::error&) {
563 
564  std::deque<define> previous_defines;
565  for(const preproc_map::value_type& preproc : old_defines_map_) {
566  previous_defines.emplace_back(new game_config::scoped_preproc_define(preproc.first));
567  }
568 
570 
571  throw;
572  }
573 
575 }
577 {
578  game_config::scoped_preproc_define multiplayer("MULTIPLAYER", is_mp);
579  game_config::scoped_preproc_define test("TEST", is_test);
580  game_config::scoped_preproc_define mptest("MP_TEST", cmdline_opts_.mptest && is_mp);
581 ///During an mp game the default difficuly define is also defined so better already load it now if we alreeady must reload config cache.
583 
584  typedef std::unique_ptr<game_config::scoped_preproc_define> define;
585  try{
587  }
588  catch(game::error&) {
590 
591  std::deque<define> previous_defines;
592  for (const preproc_map::value_type& preproc : old_defines_map_) {
593  previous_defines.emplace_back(new game_config::scoped_preproc_define(preproc.first));
594  }
595 
597 
598  throw;
599  }
600 }
601 
void set_config(config &cfg)
Resets all data based on the provided config.
Definition: types.cpp:1114
Don't reload if the previous defines include the new defines.
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:417
std::vector< char_t > string
bool mptest
True if –mp-test was given on the command line.
std::string era()
Definition: game.cpp:700
game_classification * classification
Definition: resources.cpp:34
void append(const config &cfg)
Append data from another config object to this one.
Definition: config.cpp:287
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
config & find_child(config_key_type key, const std::string &name, const std::string &value)
Returns the first child of tag key with a name attribute containing value.
Definition: config.cpp:780
static void set_known_themes(const config *cfg)
Definition: theme.cpp:876
void merge_children(const std::string &key)
All children with the given key will be merged into the first element with that key.
Definition: config.cpp:323
bool noaddons
True if –noaddons was given on the command line. Disables the loading of all add-ons.
logger & info()
Definition: log.cpp:91
void lock()
Lock the transaction so no more macros are added.
void set_scope_active(scope s, bool set)
child_itors child_range(config_key_type key)
Definition: config.cpp:360
filesystem::binary_paths_manager paths_manager_
static void progress(loading_stage stage=loading_stage::none)
const std::string DEFAULT_DIFFICULTY
The default difficulty setting for campaigns.
#define ERR_CONFIG
unit_type_data unit_types
Definition: types.cpp:1453
Don't reload if the previous defines equal the new defines.
static lg::log_domain log_config("config")
bool empty() const
Definition: config.cpp:828
void load_config(const config &v)
static void add_color_info(const config &v, bool build_defaults)
version_info get_addon_version_info(const std::string &addon)
Returns a particular installed add-on's version information.
Definition: manager.cpp:383
Used to set and unset scoped defines to preproc_map.
void call_in_main_thread(const std::function< void(void)> &f)
Definition: events.cpp:743
void flush_cache()
Definition: image.cpp:211
void clear_binary_paths_cache()
static void extract_preload_scripts(const config &game_config)
static game_config_manager * get()
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:89
void splice_children(config &src, const std::string &key)
Moves all the children with tag key from src to this.
Definition: config.cpp:573
void clear_children(T...keys)
Definition: config.hpp:510
std::string campaign_define
If there is a define the campaign uses to customize data.
const preproc_map & get_preproc_map() const
void get_config(const std::string &path, config &cfg)
Gets a config object from given path.
static UNUSEDNOWARN std::string _n(const char *str1, const char *str2, int n)
Definition: gettext.hpp:93
void set_force_valid_cache(bool force)
Enable/disable cache validation.
void set_core_id(const std::string &core_id)
Definition: general.cpp:321
static game_config_manager * singleton
std::string path
Definition: game_config.cpp:56
boost::optional< std::string > test
Non-empty if –test was given on the command line. Goes directly into test mode, into a scenario...
void init_textdomains(const config &cfg)
Initializes the list of textdomains from a configuration object.
Definition: language.cpp:289
bool multiplayer
True if –multiplayer was given on the command line. Goes directly into multiplayer mode...
void refresh_addon_version_info_cache()
Refreshes the per-session cache of add-on's version information structs.
Definition: manager.cpp:341
std::string campaign
The id of the campaign being played.
void deactivate_all_scopes()
log_domain & general()
Definition: log.cpp:105
std::string era_define
If there is a define the era uses to customize data.
void set_use_cache(bool use)
Enable/disable caching.
void clear_defines()
Clear stored defines map to default values.
void get_files_in_dir(const std::string &dir, std::vector< std::string > *files, std::vector< std::string > *dirs=nullptr, file_name_option mode=FILE_NAME_ONLY, file_filter_option filter=NO_FILTER, file_reorder_option reorder=DONT_REORDER, file_tree_checksum *checksum=nullptr)
Populates 'files' with all the files and 'dirs' with all the directories in dir.
game_config_manager(const commandline_options &cmdline_opts, const bool jump_to_editor)
bool nocache
True if –nocache was given on the command line. Disables cache usage.
logger & err()
Definition: log.cpp:79
std::vector< std::string > campaign_xtra_defines
more customization of data
std::string get_wml_location(const std::string &filename, const std::string &current_dir=std::string())
Returns a complete path to the actual WML file or directory or an empty string if the file isn't pres...
void load_game_config_for_create(bool is_mp, bool is_test=false)
Game configuration data as global variables.
Definition: build_info.cpp:53
const config & child_or_empty(config_key_type key) const
Returns the first child with the given key, or an empty config if there is none.
Definition: config.cpp:450
An exception object used when an IO error occurs.
Definition: filesystem.hpp:46
const config & game_config() const
void reset_color_info()
std::string scenario_define
If there is a define the scenario uses to customize data.
std::vector< std::string > mod_defines
If there are defines the modifications use to customize data.
Definitions related to theme-support.
Definitions for the terrain builder.
static void display(const std::string &summary, const std::string &post_summary, const std::vector< std::string > &files, const std::string &details)
The display function; see modal_dialog for more information.
Definition: wml_error.hpp:43
Represents version numbers.
Definition: version.hpp:43
config & add_child(config_key_type key)
Definition: config.cpp:473
const file_tree_checksum & data_tree_checksum(bool reset=false)
Get the time at which the data/ tree was last modified at.
std::string difficulty
The difficulty level the game is being played on.
std::string core_id()
Definition: general.cpp:315
void set_about(const config &cfg)
Regenerates the credits config.
Definition: about.cpp:55
Used to share macros between cache objects You have to create transaction object to load all macros t...
std::string hash() const
Definition: config.cpp:1254
static void display(std::function< void()> f)
void load_game_config_for_game(const game_classification &classification)
static void set_terrain_rules_cfg(const config &cfg)
Set the config where we will parse the global terrain rules.
Definition: builder.cpp:290
Base class for all the errors encountered by the engine.
Definition: exceptions.hpp:29
void load_hotkeys(const config &cfg, bool set_as_default)
Iterates through all hotkeys present in the config struct and creates and adds them to the hotkey lis...
std::string get_addons_dir()
Managing the AIs configuration - headers.
Standard logging facilities (interface).
std::string message
Definition: exceptions.hpp:31
version_info version
const commandline_options & cmdline_opts_
bool validcache
True if –validcache was given on the command line. Makes Wesnoth assume the cache is valid...
bool init_strings(const config &cfg)
Initializes certain English strings.
Definition: language.cpp:312
game_config::config_cache & cache_
std::map< std::string, struct preproc_define > preproc_map
#define e
std::string addon_title
static void init(const config &game_config)
Init the parameters of ai configuration parser.
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:93
Interfaces for manipulating version numbers of engine, add-ons, etc.
static map_location::DIRECTION n
bool init_game_config(FORCE_RELOAD_CONFIG force_reload)
bool file_exists(const std::string &name)
Returns true if a file or directory with such name already exists.
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:865
void load_game_config(FORCE_RELOAD_CONFIG force_reload, game_classification const *classification=nullptr)
void recheck_filetree_checksum()
Force cache checksum validation.
void load_game_config_with_loadscreen(FORCE_RELOAD_CONFIG force_reload, game_classification const *classification=nullptr)