The Battle for Wesnoth  1.13.11+dev
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
game_state.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2014 - 2018 by Chris Beck <render787@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 
15 #include "game_state.hpp"
16 
17 #include "actions/undo.hpp"
18 #include "game_board.hpp"
19 #include "game_data.hpp"
20 #include "game_events/manager.hpp"
21 #include "log.hpp"
22 #include "map/map.hpp"
23 #include "pathfind/pathfind.hpp"
24 #include "pathfind/teleport.hpp"
25 #include "play_controller.hpp"
26 #include "preferences/game.hpp"
27 #include "random_deterministic.hpp"
28 #include "reports.hpp"
30 #include "teambuilder.hpp"
31 #include "units/unit.hpp"
32 #include "whiteboard/manager.hpp"
34 
35 #include "utils/functional.hpp"
36 #include <SDL_timer.h>
37 
38 #include <algorithm>
39 #include <set>
40 
41 static lg::log_domain log_engine("engine");
42 #define LOG_NG LOG_STREAM(info, log_engine)
43 #define DBG_NG LOG_STREAM(debug, log_engine)
44 
46  gamedata_(level),
47  board_(tdata, level),
48  tod_manager_(level),
49  pathfind_manager_(new pathfind::manager(level)),
50  reports_(new reports()),
51  lua_kernel_(new game_lua_kernel(*this, pc, *reports_)),
52  ai_manager_(),
53  events_manager_(new game_events::manager()),
54  //TODO: this construct units (in dimiss undo action) but resrouces:: are not available yet,
55  // so we might want to move the innitialisation of undo_stack_ to game_state::init
56  undo_stack_(new actions::undo_list(level.child("undo_stack"))),
57  player_number_(level["playing_team"].to_int() + 1),
58  init_side_done_(level["init_side_done"].to_bool(false)),
59  start_event_fired_(!level["playing_team"].empty()),
60  server_request_number_(level["server_request_number"].to_int()),
61  first_human_team_(-1)
62 {
63  lua_kernel_->load_core();
64  if(const config& endlevel_cfg = level.child("end_level_data")) {
65  end_level_data el_data;
66  el_data.read(endlevel_cfg);
67  el_data.transient.carryover_report = false;
68  end_level_data_ = el_data;
69  }
70 }
71 
73  gamedata_(level),
74  board_(board),
75  tod_manager_(level),
76  pathfind_manager_(new pathfind::manager(level)),
77  reports_(new reports()),
78  lua_kernel_(new game_lua_kernel(*this, pc, *reports_)),
79  ai_manager_(),
80  events_manager_(new game_events::manager()),
81  player_number_(level["playing_team"].to_int() + 1),
82  end_level_data_(),
83  init_side_done_(level["init_side_done"].to_bool(false)),
84  start_event_fired_(!level["playing_team"].empty()),
85  server_request_number_(level["server_request_number"].to_int()),
86  first_human_team_(-1)
87 {
88  lua_kernel_->load_core();
89  events_manager_->read_scenario(level);
90  if(const config& endlevel_cfg = level.child("end_level_data")) {
91  end_level_data el_data;
92  el_data.read(endlevel_cfg);
93  el_data.transient.carryover_report = false;
94  end_level_data_ = el_data;
95  }
96 }
97 
98 
100 
101 static int placing_score(const config& side, const gamemap& map, const map_location& pos)
102 {
103  int positions = 0, liked = 0;
104  const t_translation::ter_list terrain = t_translation::read_list(side["terrain_liked"]);
105 
106  for(int i = -8; i != 8; ++i) {
107  for(int j = -8; j != +8; ++j) {
108  const map_location pos2 = pos.plus(i, j);
109  if(map.on_board(pos2)) {
110  ++positions;
111  if(std::count(terrain.begin(),terrain.end(),map[pos2])) {
112  ++liked;
113  }
114  }
115  }
116  }
117 
118  return (100*liked)/positions;
119 }
120 
121 struct placing_info {
122 
124  side(0),
125  score(0),
126  pos()
127  {
128  }
129 
130  int side, score;
132 };
133 
134 static bool operator<(const placing_info& a, const placing_info& b) { return a.score > b.score; }
135 
136 
138 {
139  std::vector<placing_info> placings;
140 
141  int num_pos = board_.map().num_valid_starting_positions();
142 
143  int side_num = 1;
144  for(const config &side : level.child_range("side"))
145  {
146  for(int p = 1; p <= num_pos; ++p) {
147  const map_location& pos = board_.map().starting_position(p);
148  int score = placing_score(side, board_.map(), pos);
149  placing_info obj;
150  obj.side = side_num;
151  obj.score = score;
152  obj.pos = pos;
153  placings.push_back(obj);
154  }
155  ++side_num;
156  }
157 
158  std::stable_sort(placings.begin(),placings.end());
159  std::set<int> placed;
160  std::set<map_location> positions_taken;
161 
162  for (std::vector<placing_info>::const_iterator i = placings.begin(); i != placings.end() && int(placed.size()) != side_num - 1; ++i) {
163  if(placed.count(i->side) == 0 && positions_taken.count(i->pos) == 0) {
164  placed.insert(i->side);
165  positions_taken.insert(i->pos);
166  board_.map_->set_starting_position(i->side,i->pos);
167  LOG_NG << "placing side " << i->side << " at " << i->pos << std::endl;
168  }
169  }
170 }
171 
173 {
174  events_manager_->read_scenario(level);
176  if (level["modify_placing"].to_bool()) {
177  LOG_NG << "modifying placing..." << std::endl;
179  }
180 
181  LOG_NG << "initialized time of day regions... " << (SDL_GetTicks() - pc.ticks()) << std::endl;
182  for (const config &t : level.child_range("time_area")) {
184  }
185 
186  LOG_NG << "initialized teams... " << (SDL_GetTicks() - pc.ticks()) << std::endl;
187 
188  board_.teams_.resize(level.child_count("side"));
189 
190  std::vector<team_builder_ptr> team_builders;
191 
192  int team_num = 0;
193  for (const config &side : level.child_range("side"))
194  {
195  if (first_human_team_ == -1) {
196  const std::string &controller = side["controller"];
197  if (controller == "human" && side["is_local"].to_bool(true)) {
198  first_human_team_ = team_num;
199  }
200  }
201  ++team_num;
203  board_.teams_, level, board_, team_num);
204  build_team_stage_one(tb_ptr);
205  team_builders.push_back(tb_ptr);
206  }
207  //Initialize the lua kernel before the units are created.
208  lua_kernel_->initialize(level);
209 
210  {
211  //sync traits of start units and the random start time.
213 
215 
216  for(team_builder_ptr tb_ptr : team_builders)
217  {
218  build_team_stage_two(tb_ptr);
219  }
220  for(size_t i = 0; i < board_.teams_.size(); i++) {
221  // Labels from players in your ignore list default to hidden
222  if(preferences::is_ignored(board_.teams_[i].current_player())) {
223  std::string label_cat = "side:" + std::to_string(i + 1);
224  board_.hidden_label_categories_ref().push_back(label_cat);
225  }
226  }
227  }
228 }
229 
231 {
232  lua_kernel_->set_game_display(gd);
233 }
234 
235 void game_state::write(config& cfg) const
236 {
237  cfg["init_side_done"] = init_side_done_;
238  if(gamedata_.phase() == game_data::PLAY) {
239  cfg["playing_team"] = player_number_ - 1;
240  }
241  cfg["server_request_number"] = server_request_number_;
242  //Call the lua save_game functions
243  lua_kernel_->save_game(cfg);
244 
245  //Write the game events.
246  events_manager_->write_events(cfg);
247 
248  //Write the map, unit_map, and teams info
249  board_.write_config(cfg);
250 
251  //Write the tod manager, and time areas
253 
254  //write out the current state of the map
255  cfg.merge_with(pathfind_manager_->to_config());
256 
257  //Write the game data, including wml vars
259 
260  // Preserve the undo stack so that fog/shroud clearing is kept accurate.
261  undo_stack_->write(cfg.add_child("undo_stack"));
262 
263  if(end_level_data_.get_ptr() != nullptr) {
264  end_level_data_->write(cfg.add_child("end_level_data"));
265  }
266 }
267 
268 namespace {
269  struct castle_cost_calculator : pathfind::cost_calculator
270  {
271  castle_cost_calculator(const gamemap& map, const team & view_team) :
272  map_(map),
273  viewer_(view_team),
274  use_shroud_(view_team.uses_shroud())
275  {}
276 
277  virtual double cost(const map_location& loc, const double) const
278  {
279  if(!map_.is_castle(loc))
280  return 10000;
281 
282  if ( use_shroud_ && viewer_.shrouded(loc) )
283  return 10000;
284 
285  return 1;
286  }
287 
288  private:
289  const gamemap& map_;
290  const team& viewer_;
291  const bool use_shroud_; // Allows faster checks when shroud is disabled.
292  };
293 }//anonymous namespace
294 
295 
296 /**
297  * Checks to see if a leader at @a leader_loc could recruit somewhere.
298  * This takes into account terrain, shroud (for side @a side), and the presence
299  * of visible units.
300  * The behavior for an invalid @a side is subject to change for future needs.
301  */
302 bool game_state::can_recruit_from(const map_location& leader_loc, int side) const
303 {
304  const gamemap& map = board_.map();
305 
306  if(!map.is_keep(leader_loc)) {
307  return false;
308  }
309 
310  try {
311  return pathfind::find_vacant_tile(leader_loc, pathfind::VACANT_CASTLE, nullptr, &board_.get_team(side))
313  } catch(const std::out_of_range&) {
314  // Invalid side specified.
315  // Currently this cannot happen, but it could conceivably be used in
316  // the future to request that shroud and visibility be ignored. Until
317  // that comes to pass, just return.
318  return false;
319  }
320 }
321 
322 bool game_state::can_recruit_from(const unit& leader) const
323 {
324  return can_recruit_from(leader.get_location(), leader.side());
325 }
326 
327 
328 /**
329  * Checks to see if a leader at @a leader_loc could recruit on @a recruit_loc.
330  * This takes into account terrain, shroud (for side @a side), and whether or
331  * not there is already a visible unit at recruit_loc.
332  * The behavior for an invalid @a side is subject to change for future needs.
333  */
334 bool game_state::can_recruit_on(const map_location& leader_loc, const map_location& recruit_loc, int side) const
335 {
336  const gamemap& map = board_.map();
337 
338  if(!map.is_castle(recruit_loc)) {
339  return false;
340  }
341 
342  if(!map.is_keep(leader_loc)) {
343  return false;
344  }
345 
346  try {
347  const team& view_team = board_.get_team(side);
348 
349  if(view_team.shrouded(recruit_loc)) {
350  return false;
351  }
352 
353  if(board_.has_visible_unit(recruit_loc, view_team)) {
354  return false;
355  }
356 
357  castle_cost_calculator calc(map, view_team);
358 
359  // The limit computed in the third argument is more than enough for
360  // any convex castle on the map. Strictly speaking it could be
361  // reduced to sqrt(map.w()**2 + map.h()**2).
363  pathfind::a_star_search(leader_loc, recruit_loc, map.w() + map.h(), calc, map.w(), map.h());
364 
365  return !rt.steps.empty();
366  } catch(const std::out_of_range&) {
367  // Invalid side specified.
368  // Currently this cannot happen, but it could conceivably be used in
369  // the future to request that shroud and visibility be ignored. Until
370  // that comes to pass, just return.
371  return false;
372  }
373 }
374 
375 bool game_state::can_recruit_on(const unit& leader, const map_location& recruit_loc) const
376 {
377  return can_recruit_on(leader.get_location(), recruit_loc, leader.side());
378 }
379 
381 {
382  unit_map::const_iterator leader = board_.units().find(hex);
383  if ( leader != board_.units().end() ) {
384  return leader->can_recruit() && leader->side() == side && can_recruit_from(*leader);
385  } else {
386  // Look for a leader who can recruit on last_hex.
387  for ( leader = board_.units().begin(); leader != board_.units().end(); ++leader) {
388  if ( leader->can_recruit() && leader->side() == side && can_recruit_on(*leader, hex) ) {
389  return true;
390  }
391  }
392  }
393  // No leader found who can recruit at last_hex.
394  return false;
395 }
396 
398 {
399  return this->events_manager_->wml_menu_items();
400 }
401 
403 {
404  return this->events_manager_->wml_menu_items();
405 }
void read(const config &cfg)
std::unique_ptr< gamemap > map_
Definition: game_board.hpp:56
const std::unique_ptr< actions::undo_list > undo_stack_
undo_stack_ is never nullptr.
Definition: game_state.hpp:56
Game board class.
Definition: game_board.hpp:50
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
PHASE phase() const
Definition: game_data.hpp:76
unit_iterator end()
Definition: map.hpp:415
std::vector< char_t > string
int ticks() const
void build_team_stage_two(team_builder_ptr tb_ptr)
std::unique_ptr< game_lua_kernel > lua_kernel_
Definition: game_state.hpp:50
ter_list read_list(const std::string &str, const ter_layer filler)
Reads a list of terrains from a string, when reading the.
virtual const unit_map & units() const override
Definition: game_board.hpp:114
This class represents a single unit of a specific type.
Definition: unit.hpp:100
bool shrouded(const map_location &loc) const
Definition: team.cpp:633
void write_config(config &cfg) const
Definition: game_board.cpp:334
std::vector< std::string > & hidden_label_categories_ref()
game_events::wmi_manager & get_wml_menu_items()
Definition: game_state.cpp:397
#define a
map_location find_vacant_tile(const map_location &loc, VACANT_TILE_TYPE vacancy, const unit *pass_check, const team *shroud_check, const game_board *board)
Function that will find a location on the board that is as near to loc as possible, but which is unoccupied by any units.
Definition: pathfind.cpp:54
int first_human_team_
Definition: game_state.hpp:69
child_itors child_range(config_key_type key)
Definition: config.cpp:360
int server_request_number_
Definition: game_state.hpp:63
bool can_recruit_on(const map_location &leader_loc, const map_location &recruit_loc, int side) const
Checks to see if a leader at leader_loc could recruit on recruit_loc.
Definition: game_state.cpp:334
static void progress(loading_stage stage=loading_stage::none)
void resolve_random(randomness::rng &r)
handles random_start_time, should be called before the game starts.
Definition: tod_manager.cpp:79
virtual const gamemap & map() const override
Definition: game_board.hpp:109
unit_iterator begin()
Definition: map.hpp:405
map_location plus(int x_diff, int y_diff) const
Definition: location.hpp:124
bool init_side_done_
Definition: game_state.hpp:60
const std::unique_ptr< game_events::manager > events_manager_
Definition: game_state.hpp:52
Unit and team statistics.
config to_config() const
#define b
void merge_with(const config &c)
Merge config 'c' into this config, overwriting this config's values.
Definition: config.cpp:1111
unsigned child_count(config_key_type key) const
Definition: config.cpp:388
This class stores all the data for a single 'side' (in game nomenclature).
Definition: team.hpp:44
team & get_team(int i)
Definition: game_board.hpp:104
std::vector< map_location > steps
Definition: pathfind.hpp:134
bool side_can_recruit_on(int side, map_location loc) const
Checks if any of the sides leaders can recruit at a location.
Definition: game_state.cpp:380
map_location starting_position(int side) const
Definition: map.cpp:323
std::vector< team > teams_
Definition: game_board.hpp:53
RAII class to use rng_deterministic in the current scope.
Structure which holds a single route between one location and another.
Definition: pathfind.hpp:131
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1141
void write_snapshot(config &cfg) const
Definition: game_data.cpp:126
int w() const
Effective map width.
Definition: map.hpp:90
Encapsulates the map of the game.
Definition: map.hpp:34
tod_manager tod_manager_
Definition: game_state.hpp:47
std::unique_ptr< pathfind::manager > pathfind_manager_
Definition: game_state.hpp:48
bool carryover_report
Should a summary of the scenario outcome be displayed?
static const map_location & null_location()
Definition: location.hpp:224
static const ::config * terrain
The terrain used to create the cache.
Definition: minimap.cpp:130
static int placing_score(const config &side, const gamemap &map, const map_location &pos)
Definition: game_state.cpp:101
bool is_ignored(const std::string &nick)
Definition: game.cpp:302
#define LOG_NG
Definition: game_state.cpp:42
Encapsulates the map of the game.
Definition: location.hpp:42
plain_route a_star_search(const map_location &src, const map_location &dst, double stop_at, const cost_calculator &calc, const size_t width, const size_t height, const teleport_map *teleports, bool border)
Domain specific events.
Definition: action_wml.cpp:88
transient_end_level transient
const randomness::mt_rng & rng() const
Definition: game_data.hpp:65
bool has_visible_unit(const map_location &loc, const team &team, bool see_all=false) const
Definition: game_board.cpp:178
void write(config &cfg) const
Definition: game_state.cpp:235
int h() const
Effective map height.
Definition: map.hpp:93
mock_party p
std::shared_ptr< team_builder > team_builder_ptr
Definition: teambuilder.hpp:23
static bool operator<(const placing_info &a, const placing_info &b)
Definition: game_state.cpp:134
size_t i
Definition: function.cpp:933
bool can_recruit_from(const map_location &leader_loc, int side) const
Checks to see if a leader at leader_loc could recruit somewhere.
Definition: game_state.cpp:302
boost::optional< end_level_data > end_level_data_
Definition: game_state.hpp:59
game_data gamedata_
Definition: game_state.hpp:45
Additional information on the game outcome which can be provided by WML.
bool is_castle(const map_location &loc) const
Definition: map.cpp:70
game_state(const config &level, play_controller &, const ter_data_cache &tdata)
Definition: game_state.cpp:45
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:57
void build_team_stage_one(team_builder_ptr tb_ptr)
void init(const config &level, play_controller &)
Definition: game_state.cpp:172
config & add_child(config_key_type key)
Definition: config.cpp:473
bool on_board(const map_location &loc) const
Tell if a location is on the map.
Definition: map.cpp:369
void set_game_display(game_display *)
Definition: game_state.cpp:230
double t
Definition: astarsearch.cpp:64
virtual double cost(const map_location &loc, const double so_far) const =0
void add_time_area(const gamemap &map, const config &cfg)
Adds a new local time area from config, making it follow its own time-of-day sequence.
game_board board_
Definition: game_state.hpp:46
int num_valid_starting_positions() const
Definition: map.cpp:328
map_location pos
Definition: game_state.cpp:131
Various functions that implement the undoing (and redoing) of in-game commands.
Standard logging facilities (interface).
std::vector< terrain_code > ter_list
Definition: translation.hpp:83
int player_number_
Definition: game_state.hpp:57
static lg::log_domain log_engine("engine")
team_builder_ptr create_team_builder(const config &side_cfg, std::vector< team > &teams, const config &level, game_board &board, int num)
void place_sides_in_preferred_locations(const config &level)
Definition: game_state.cpp:137
unit_iterator find(size_t id)
Definition: map.cpp:311
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:93
This module contains various pathfinding functions and utilities.
int side() const
The side this unit belongs to.
Definition: unit.hpp:244
bool is_keep(const map_location &loc) const
Definition: map.cpp:72
std::shared_ptr< terrain_type_data > ter_data_cache