The Battle for Wesnoth  1.13.10+dev
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
advancement.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2016 - 2017 by the Battle for Wesnoth Project http://www.wesnoth.org/
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or
7  (at your option) any later version.
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY.
10 
11  See the COPYING file for more details.
12 */
13 
14 /**
15  * @file
16  * Fighting.
17  */
18 
19 #include "actions/advancement.hpp"
20 
21 #include "actions/vision.hpp"
22 
24 #include "game_events/pump.hpp"
25 #include "preferences/game.hpp"
26 #include "game_data.hpp" //resources::gamedata->phase()
28 #include "gui/widgets/window.hpp" //gui2::window::OK
29 #include "log.hpp"
30 #include "play_controller.hpp" //resources::controller
31 #include "random.hpp"
32 #include "resources.hpp"
33 #include "statistics.hpp"
34 #include "synced_user_choice.hpp"
35 #include "units/unit.hpp"
36 #include "units/abilities.hpp"
38 #include "units/udisplay.hpp"
39 #include "units/helper.hpp" //number_of_possible_advances
40 #include "whiteboard/manager.hpp"
41 
42 static lg::log_domain log_engine("engine");
43 #define DBG_NG LOG_STREAM(debug, log_engine)
44 #define LOG_NG LOG_STREAM(info, log_engine)
45 #define WRN_NG LOG_STREAM(err, log_engine)
46 #define ERR_NG LOG_STREAM(err, log_engine)
47 
48 static lg::log_domain log_config("config");
49 #define LOG_CF LOG_STREAM(info, log_config)
50 
51 static lg::log_domain log_display("display");
52 #define LOG_DP LOG_STREAM(info, log_display)
53 
54 
55 namespace
56 {
57  int advance_unit_dialog(const map_location &loc)
58  {
59  const unit& u = *resources::gameboard->units().find(loc);
60  std::vector<unit_const_ptr> previews;
61 
62  for (const std::string& advance : u.advances_to()) {
63  preferences::encountered_units().insert(advance);
64  previews.push_back(get_advanced_unit(u, advance));
65  }
66 
67  size_t num_real_advances = previews.size();
68  bool always_display = false;
69 
70  for (const config& advance : u.get_modification_advances()) {
71  if (advance["always_display"]) {
72  always_display = true;
73  }
74  previews.push_back(get_amla_unit(u, advance));
75  }
76 
77  if (previews.size() > 1 || always_display) {
78  gui2::dialogs::unit_advance dlg(previews, num_real_advances);
79 
80  dlg.show();
81 
82  if (dlg.get_retval() == gui2::window::OK) {
83  return dlg.get_selected_index();
84  }
85 
86  // This should be unreachable, since canceling is disabled for the dialog
87  assert(false && "Unit advance dialog was cancelled, which should be impossible.");
88  }
89 
90  return 0;
91  }
92 
93  bool animate_unit_advancement(const map_location &loc, size_t choice, const bool &fire_event, const bool animate)
94  {
95  const events::command_disabler cmd_disabler;
96 
98  if (u == resources::gameboard->units().end()) {
99  LOG_DP << "animate_unit_advancement suppressed: invalid unit\n";
100  return false;
101  }
102  else if (!u->advances()) {
103  LOG_DP << "animate_unit_advancement suppressed: unit does not advance\n";
104  return false;
105  }
106 
107  const std::vector<std::string>& options = u->advances_to();
108  std::vector<config> mod_options = u->get_modification_advances();
109 
110  if (choice >= options.size() + mod_options.size()) {
111  LOG_DP << "animate_unit_advancement suppressed: invalid option\n";
112  return false;
113  }
114 
115  // When the unit advances, it fades to white, and then switches
116  // to the new unit, then fades back to the normal color
117 
118  if (animate && !CVideo::get_singleton().update_locked()) {
119  unit_animator animator;
120  bool with_bars = true;
121  animator.add_animation(&*u, "levelout", u->get_location(), map_location(), 0, with_bars);
122  animator.start_animations();
123  animator.wait_for_end();
124  }
125 
126  if (choice < options.size()) {
127  // chosen_unit is not a reference, since the unit may disappear at any moment.
128  std::string chosen_unit = options[choice];
129  ::advance_unit(loc, chosen_unit, fire_event);
130  }
131  else {
132  const config &mod_option = mod_options[choice - options.size()];
133  ::advance_unit(loc, &mod_option, fire_event);
134  }
135 
136  u = resources::gameboard->units().find(loc);
138 
139  if (animate && u != resources::gameboard->units().end() && !CVideo::get_singleton().update_locked()) {
140  unit_animator animator;
141  animator.add_animation(&*u, "levelin", u->get_location(), map_location(), 0, true);
142  animator.start_animations();
143  animator.wait_for_end();
144  animator.set_all_standing();
146  events::pump();
147  }
148 
150 
151  return true;
152  }
153 
154  class unit_advancement_choice : public mp_sync::user_choice
155  {
156  public:
157  unit_advancement_choice(const map_location& loc, int total_opt, int side_num, const ai::unit_advancements_aspect* ai_advancement, bool force_dialog)
158  : loc_ (loc), nb_options_(total_opt), side_num_(side_num), ai_advancement_(ai_advancement), force_dialog_(force_dialog)
159  {
160  }
161 
162  virtual ~unit_advancement_choice()
163  {
164  }
165 
166  virtual config query_user(int /*side*/) const
167  {
168  //the 'side' parameter might differ from side_num_-
169  int res = 0;
170  team t = resources::gameboard->get_team(side_num_);
171  //i wonder how this got included here ?
172  bool is_mp = resources::controller->is_networked_mp();
173  bool is_current_side = resources::controller->current_side() == side_num_;
174  //note, that the advancements for networked sides are also determined on the current playing side.
175 
176  //to make mp games equal we only allow selecting advancements to the current side.
177  //otherwise we'd give an unfair advantage to the side that hosts ai sides if units advance during ai turns.
178  if(!CVideo::get_singleton().non_interactive() && (force_dialog_ || (t.is_local_human() && !t.is_idle() && (is_current_side || !is_mp))))
179  {
180  res = advance_unit_dialog(loc_);
181  }
182  else if(t.is_local_ai() || t.is_network_ai() || t.is_empty())
183  {
184  res = randomness::generator->get_random_int(0, nb_options_-1);
185 
186  //if ai_advancement_ is the default advancement the following code will
187  //have no effect because get_advancements returns an empty list.
188  if(ai_advancement_ != nullptr)
189  {
191  const std::vector<std::string>& options = u->advances_to();
192  const std::vector<std::string>& allowed = ai_advancement_->get_advancements(u);
193 
194  for(std::vector<std::string>::const_iterator a = options.begin(); a != options.end(); ++a) {
195  if (std::find(allowed.begin(), allowed.end(), *a) != allowed.end()){
196  res = a - options.begin();
197  break;
198  }
199  }
200  }
201 
202  }
203  else
204  {
205  //we are in the situation, that the unit is owned by a human, but he's not allowed to do this decision.
206  //because it's a mp game and it's not his turn.
207  //note that it doesn't matter whether we call randomness::generator->next_random() or rand().
208  res = randomness::generator->get_random_int(0, nb_options_-1);
209  }
210  LOG_NG << "unit at position " << loc_ << "choose advancement number " << res << "\n";
211  config retv;
212  retv["value"] = res;
213  return retv;
214 
215  }
216  virtual config random_choice(int /*side*/) const
217  {
218  config retv;
219  retv["value"] = 0;
220  return retv;
221  }
222  virtual std::string description() const
223  {
224  return "an advancement choice";
225  }
226  private:
227  const map_location loc_;
228  int nb_options_;
229  int side_num_;
230  const ai::unit_advancements_aspect* ai_advancement_;
231  bool force_dialog_;
232  };
233 }
234 
235 /*
236 advances the unit and stores data in the replay (or reads data from replay).
237 */
239 {
240  //i just don't want infinite loops...
241  // the 20 is picked rather randomly.
242  for(int advacment_number = 0; advacment_number < 20; advacment_number++)
243  {
245  //this implies u.valid()
247  return;
248  }
249 
250  if(params.fire_events_)
251  {
252  LOG_NG << "Firing pre advance event at " << params.loc_ <<".\n";
253  resources::game_events->pump().fire("pre_advance", params.loc_);
254  //TODO: maybe use id instead of location here ?.
255  u = resources::gameboard->units().find(params.loc_);
257  {
258  LOG_NG << "pre advance event aborted advancing.\n";
259  return;
260  }
261  }
262  //we don't want to let side 1 decide it during start/prestart.
263  int side_for = resources::gamedata->phase() == game_data::PLAY ? 0: u->side();
265  unit_advancement_choice(params.loc_, unit_helper::number_of_possible_advances(*u), u->side(), params.ai_advancements_, params.force_dialog_), side_for);
266  //calls actions::advance_unit.
267  bool result = animate_unit_advancement(params.loc_, selected["value"], params.fire_events_, params.animate_);
268 
269  DBG_NG << "animate_unit_advancement result = " << result << std::endl;
270  u = resources::gameboard->units().find(params.loc_);
271  // level 10 unit gives 80 XP and the highest mainline is level 5
272  if (u.valid() && u->experience() > 80)
273  {
274  WRN_NG << "Unit has too many (" << u->experience() << ") XP left; cascade leveling goes on still." << std::endl;
275  }
276  }
277  ERR_NG << "unit at " << params.loc_ << "tried to advance more than 20 times. Advancing was aborted" << std::endl;
278 }
279 
280 unit_ptr get_advanced_unit(const unit &u, const std::string& advance_to)
281 {
282  const unit_type *new_type = unit_types.find(advance_to);
283  if (!new_type) {
284  throw game::game_error("Could not find the unit being advanced"
285  " to: " + advance_to);
286  }
287  unit_ptr new_unit(new unit(u));
288  new_unit->set_experience(new_unit->experience_overflow());
289  new_unit->advance_to(*new_type);
290  new_unit->heal_fully();
291  new_unit->set_state(unit::STATE_POISONED, false);
292  new_unit->set_state(unit::STATE_SLOWED, false);
293  new_unit->set_state(unit::STATE_PETRIFIED, false);
294  new_unit->set_user_end_turn(false);
295  new_unit->set_hidden(false);
296  return new_unit;
297 }
298 
299 
300 /**
301  * Returns the AMLA-advanced version of a unit (with traits and items retained).
302  */
303 unit_ptr get_amla_unit(const unit &u, const config &mod_option)
304 {
305  unit_ptr amla_unit(new unit(u));
306  amla_unit->set_experience(amla_unit->experience_overflow());
307  amla_unit->add_modification("advancement", mod_option);
308  return amla_unit;
309 }
310 
311 
312 void advance_unit(map_location loc, const advancement_option &advance_to, bool fire_event)
313 {
315  if(!u.valid()) {
316  return;
317  }
318  // original_type is not a reference, since the unit may disappear at any moment.
319  std::string original_type = u->type_id();
320 
321  // "advance" event.
322  if(fire_event)
323  {
324  LOG_NG << "Firing advance event at " << loc <<".\n";
325  resources::game_events->pump().fire("advance",loc);
326 
327  if (!u.valid() || u->experience() < u->max_experience() ||
328  u->type_id() != original_type)
329  {
330  LOG_NG << "WML has invalidated the advancing unit. Aborting.\n";
331  return;
332  }
333  // In case WML moved the unit:
334  loc = u->get_location();
335  }
336 
337  // This is not normally necessary, but if a unit loses power when leveling
338  // (e.g. loses "jamming" or ambush), it could be discovered as a result of
339  // the advancement.
340  std::vector<int> not_seeing = actions::get_sides_not_seeing(*u);
341 
342  // Create the advanced unit.
343  bool use_amla = boost::get<std::string>(&advance_to) == nullptr;
344  unit_ptr new_unit = use_amla ? get_amla_unit(*u, *boost::get<const config*>(advance_to)) :
345  get_advanced_unit(*u, boost::get<std::string>(advance_to));
346  new_unit->set_location(loc);
347  if ( !use_amla )
348  {
349  statistics::advance_unit(*new_unit);
350  preferences::encountered_units().insert(new_unit->type_id());
351  LOG_CF << "Added '" << new_unit->type_id() << "' to the encountered units.\n";
352  }
354  resources::whiteboard->on_kill_unit();
355  u = resources::gameboard->units().insert(new_unit).first;
356 
357  // Update fog/shroud.
358  actions::shroud_clearer clearer;
359  clearer.clear_unit(loc, *new_unit);
360 
361  // "post_advance" event.
362  if(fire_event)
363  {
364  LOG_NG << "Firing post_advance event at " << loc << ".\n";
365  resources::game_events->pump().fire("post_advance",loc);
366  }
367 
368  // "sighted" event(s).
369  clearer.fire_events();
370  if ( u.valid() )
371  actions::actor_sighted(*u, &not_seeing);
372 
373  resources::whiteboard->on_gamestate_change();
374 }
play_controller * controller
Definition: resources.cpp:21
bool is_local_ai() const
Definition: team.hpp:265
virtual std::string description() const
config get_user_choice(const std::string &name, const user_choice &uch, int side=0)
Dialog is closed with ok button.
Definition: window.hpp:101
bool fire_event(const ui_event event, std::vector< std::pair< widget *, ui_event >> &event_chain, widget *dispatcher, widget *w, F &&...params)
Helper function for fire_event.
PHASE phase() const
Definition: game_data.hpp:76
virtual const unit_map & units() const
Definition: game_board.hpp:97
std::vector< char_t > string
const ai::unit_advancements_aspect * ai_advancements_
Definition: advancement.hpp:50
#define WRN_NG
Definition: advancement.cpp:45
void start_animations()
Definition: animation.cpp:1385
bool invalidate(const map_location &loc)
Function to invalidate a specific tile for redrawing.
Definition: display.cpp:3023
This class represents a single unit of a specific type.
Definition: unit.hpp:100
bool clear_unit(const map_location &view_loc, team &view_team, size_t viewer_id, int sight_range, bool slowed, const movetype::terrain_costs &costs, const map_location &real_loc, const std::set< map_location > *known_units=nullptr, size_t *enemy_count=nullptr, size_t *friend_count=nullptr, move_unit_spectator *spectator=nullptr, bool instant=true)
Clears shroud (and fog) around the provided location for view_team based on sight_range, costs, and slowed.
Definition: vision.cpp:330
Various functions implementing vision (through fog of war and shroud).
umap_retval_pair_t insert(unit_ptr p)
Inserts the unit pointed to by p into the map.
Definition: map.cpp:135
#define a
bool will_certainly_advance(const unit_map::iterator &u)
Encapsulates the logic for deciding whether an iterator u points to a unit that can advance...
Definition: helper.cpp:30
game_display * screen
Definition: resources.cpp:27
void add_animation(const unit *animated_unit, const unit_animation *animation, const map_location &src=map_location::null_location(), bool with_bars=false, const std::string &text="", const color_t text_color={0, 0, 0})
Definition: animation.cpp:1327
This file contains the window object, this object is a top level container which has the event manage...
const std::vector< std::string > & advances_to() const
Gets the possible types this unit can advance to on level-up.
Definition: unit.hpp:144
void invalidate_unit()
Function to invalidate that unit status displayed on the sidebar.
The unit is poisoned - it loses health each turn.
Definition: unit.hpp:721
unit_type_data unit_types
Definition: types.cpp:1455
The unit is petrified - it cannot move or be attacked.
Definition: unit.hpp:722
#define ERR_NG
Definition: advancement.cpp:46
static CVideo & get_singleton()
Definition: video.hpp:43
map_location loc_
Definition: advancement.hpp:49
static lg::log_domain log_config("config")
bool show(const unsigned auto_close_time=0)
Shows the window.
unit_ptr get_advanced_unit(const unit &u, const std::string &advance_to)
Returns the advanced version of a unit (with traits and items retained).
virtual config random_choice(int side) const =0
A single unit type that the player may recruit.
Definition: types.hpp:43
game_data * gamedata
Definition: resources.cpp:22
unit_ptr get_amla_unit(const unit &u, const config &mod_option)
Returns the AMLA-advanced version of a unit (with traits and items retained).
#define DBG_NG
Definition: advancement.cpp:43
map_location loc_
boost::variant< std::string, const config * > advancement_option
Definition: advancement.hpp:66
const config & options()
Definition: game.cpp:570
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:94
game_events::pump_result_t fire_events()
Fires the sighted events that were earlier recorded by fog/shroud clearing.
Definition: vision.cpp:546
Various functions that implement advancements of units.
int current_side() const
Returns the number of the side whose turn it is.
The unit is slowed - it moves slower and does less damage.
Definition: unit.hpp:720
game_board * gameboard
Definition: resources.cpp:20
Interface for querying local choices.
std::string selected
bool is_local_human() const
Definition: team.hpp:264
Error used for any general game error, e.g.
Definition: game_errors.hpp:46
void invalidate_all()
Function to invalidate all tiles.
Definition: display.cpp:3013
game_events::manager * game_events
Definition: resources.cpp:24
std::vector< config > get_modification_advances() const
Gets any non-typed advanced options set by modifications.
Definition: unit.cpp:1663
virtual config query_user(int side) const =0
void pump()
Definition: events.cpp:409
advances the unit at loc if it has enough experience, maximum 20 times.
Definition: advancement.hpp:40
Encapsulates the map of the game.
Definition: location.hpp:40
std::shared_ptr< wb::manager > whiteboard
Definition: resources.cpp:35
void advance_unit(const unit &u)
Definition: statistics.cpp:540
void advance_unit(map_location loc, const advancement_option &advance_to, bool fire_event)
Function which will advance the unit at loc to 'advance_to'.
#define LOG_CF
Definition: advancement.cpp:49
bool update_locked() const
Whether the screen has been 'locked' or not.
Definition: video.cpp:353
Define the game's event mechanism.
static lg::log_domain log_display("display")
int number_of_possible_advances(const unit &u)
Determines the total number of available advancements (of any kind) for a given unit.
Definition: helper.cpp:25
std::set< std::string > & encountered_units()
Definition: game.cpp:942
int get_random_int(int min, int max)
This helper method provides a random int from the underlying generator, using results of next_random...
Definition: random.hpp:51
void advance_unit_at(const advance_unit_params &params)
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:57
pump_result_t fire(const std::string &event, const entity_location &loc1=entity_location::null_entity, const entity_location &loc2=entity_location::null_entity, const config &data=config())
Function to fire an event.
Definition: pump.cpp:491
size_t erase(const map_location &l)
Erases the unit at location l, if any.
Definition: map.cpp:298
boost::intrusive_ptr< unit > unit_ptr
Definition: ptr.hpp:29
double t
Definition: astarsearch.cpp:64
bool is_empty() const
Definition: team.hpp:256
bool find(E event, F functor)
Tests whether an event handler is available.
void set_all_standing()
Definition: animation.cpp:1501
bool is_idle() const
Definition: team.hpp:282
Standard logging facilities (interface).
bool is_network_ai() const
Definition: team.hpp:267
Class to encapsulate fog/shroud clearing and the resultant sighted events.
Definition: vision.hpp:57
const unit_type * find(const std::string &key, unit_type::BUILD_STATUS status=unit_type::FULL) const
Finds a unit_type by its id() and makes sure it is built to the specified level.
Definition: types.cpp:1273
game_events::wml_event_pump & pump()
Definition: manager.cpp:226
unit_iterator find(size_t id)
Definition: map.cpp:311
virtual bool is_networked_mp() const
bool valid() const
Definition: map.hpp:276
static lg::log_domain log_engine("engine")
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:93
std::vector< int > get_sides_not_seeing(const unit &target)
Returns the sides that cannot currently see target.
Definition: vision.cpp:595
unit_map * units
Definition: resources.cpp:34
Display units performing various actions: moving, attacking, and dying.
#define LOG_DP
Definition: advancement.cpp:52
void wait_for_end() const
Definition: animation.cpp:1444
game_events::pump_result_t actor_sighted(const unit &target, const std::vector< int > *cache)
Fires sighted events for the sides that can see target.
Definition: vision.cpp:622
#define LOG_NG
Definition: advancement.cpp:44