The Battle for Wesnoth  1.15.3+dev
attack.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
3  Part of the Battle for Wesnoth Project https://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 /**
16  * @file
17  * Fighting.
18  */
19 
20 #include "actions/attack.hpp"
21 
22 #include "actions/advancement.hpp"
23 #include "actions/vision.hpp"
24 
26 #include "formula/callable_objects.hpp"
27 #include "formula/formula.hpp"
28 #include "game_config.hpp"
29 #include "game_data.hpp"
30 #include "game_events/pump.hpp"
31 #include "gettext.hpp"
32 #include "log.hpp"
33 #include "map/map.hpp"
34 #include "mouse_handler_base.hpp"
35 #include "play_controller.hpp"
36 #include "preferences/game.hpp"
37 #include "random.hpp"
38 #include "replay.hpp"
39 #include "resources.hpp"
40 #include "statistics.hpp"
41 #include "synced_checkup.hpp"
42 #include "synced_user_choice.hpp"
43 #include "team.hpp"
44 #include "tod_manager.hpp"
45 #include "units/abilities.hpp"
47 #include "units/helper.hpp"
48 #include "units/filter.hpp"
49 #include "units/map.hpp"
50 #include "units/udisplay.hpp"
51 #include "units/unit.hpp"
52 #include "whiteboard/manager.hpp"
53 #include "wml_exception.hpp"
54 
55 static lg::log_domain log_engine("engine");
56 #define DBG_NG LOG_STREAM(debug, log_engine)
57 #define LOG_NG LOG_STREAM(info, log_engine)
58 #define WRN_NG LOG_STREAM(err, log_engine)
59 #define ERR_NG LOG_STREAM(err, log_engine)
60 
61 static lg::log_domain log_attack("engine/attack");
62 #define DBG_AT LOG_STREAM(debug, log_attack)
63 #define LOG_AT LOG_STREAM(info, log_attack)
64 #define WRN_AT LOG_STREAM(err, log_attack)
65 #define ERR_AT LOG_STREAM(err, log_attack)
66 
67 static lg::log_domain log_config("config");
68 #define LOG_CF LOG_STREAM(info, log_config)
69 
70 // ==================================================================================
71 // BATTLE CONTEXT UNIT STATS
72 // ==================================================================================
73 
75  const map_location& u_loc,
76  int u_attack_num,
77  bool attacking,
78  const unit& opp,
79  const map_location& opp_loc,
80  const_attack_ptr opp_weapon,
81  const unit_map& units)
82  : weapon(nullptr)
83  , attack_num(u_attack_num)
84  , is_attacker(attacking)
85  , is_poisoned(u.get_state(unit::STATE_POISONED))
86  , is_slowed(u.get_state(unit::STATE_SLOWED))
87  , slows(false)
88  , drains(false)
89  , petrifies(false)
90  , plagues(false)
91  , poisons(false)
92  , backstab_pos(false)
93  , swarm(false)
94  , firststrike(false)
95  , disable(false)
96  , experience(u.experience())
97  , max_experience(u.max_experience())
98  , level(u.level())
99  , rounds(1)
100  , hp(0)
101  , max_hp(u.max_hitpoints())
102  , chance_to_hit(0)
103  , damage(0)
104  , slow_damage(0)
105  , drain_percent(0)
106  , drain_constant(0)
107  , num_blows(0)
108  , swarm_min(0)
109  , swarm_max(0)
110  , plague_type()
111 {
112  // Get the current state of the unit.
113  if(attack_num >= 0) {
114  weapon = u.attacks()[attack_num].shared_from_this();
115  }
116 
117  if(u.hitpoints() < 0) {
118  LOG_CF << "Unit with " << u.hitpoints() << " hitpoints found, set to 0 for damage calculations\n";
119  hp = 0;
120  } else if(u.hitpoints() > u.max_hitpoints()) {
121  // If a unit has more hp than its maximum, the engine will fail with an
122  // assertion failure due to accessing the prob_matrix out of bounds.
123  hp = u.max_hitpoints();
124  } else {
125  hp = u.hitpoints();
126  }
127 
128  // Exit if no weapon.
129  if(!weapon) {
130  return;
131  }
132 
133  // Get the weapon characteristics as appropriate.
134  auto ctx = weapon->specials_context(&u, &opp, u_loc, opp_loc, attacking, opp_weapon);
135  boost::optional<decltype(ctx)> opp_ctx;
136 
137  if(opp_weapon) {
138  opp_ctx.emplace(opp_weapon->specials_context(&opp, &u, opp_loc, u_loc, !attacking, weapon));
139  }
140 
141  slows = weapon->bool_ability("slow");
142  drains = !opp.get_state("undrainable") && weapon->bool_ability("drains");
143  petrifies = weapon->bool_ability("petrifies");
144  poisons = !opp.get_state("unpoisonable") && weapon->bool_ability("poison") && !opp.get_state(unit::STATE_POISONED);
145  backstab_pos = is_attacker && backstab_check(u_loc, opp_loc, units, resources::gameboard->teams());
146  rounds = weapon->get_special_ability("berserk").highest("value", 1).first;
147 
148  firststrike = weapon->bool_ability("firststrike");
149 
150  {
151  const int distance = distance_between(u_loc, opp_loc);
152  const bool out_of_range = distance > weapon->max_range() || distance < weapon->min_range();
153  disable = weapon->get_special_bool("disable") || out_of_range;
154  }
155 
156  // Handle plague.
157  unit_ability_list plague_specials = weapon->get_specials("plague");
158  unit_ability_list alt_plague_specials = weapon->get_special_ability("plague");
159  if(!alt_plague_specials.empty() && plague_specials.empty()){
160  plague_specials = alt_plague_specials;
161  }
162  plagues = !opp.get_state("unplagueable") && !plague_specials.empty() &&
163  opp.undead_variation() != "null" && !resources::gameboard->map().is_village(opp_loc);
164 
165  if(plagues) {
166  plague_type = (*plague_specials.front().first)["type"].str();
167 
168  if(plague_type.empty()) {
169  plague_type = u.type().base_id();
170  }
171  }
172 
173  // Compute chance to hit.
174  signed int cth = opp.defense_modifier(resources::gameboard->map().get_terrain(opp_loc)) + weapon->accuracy()
175  - (opp_weapon ? opp_weapon->parry() : 0);
176 
177  cth = utils::clamp(cth, 0, 100);
178 
179  unit_ability_list cth_specials = weapon->get_special_ability("chance_to_hit");
180  unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos);
181  cth = cth_effects.get_composite_value();
182 
183 
184  if(opp.get_state("invulnerable")) {
185  cth = 0;
186  }
187 
188  chance_to_hit = utils::clamp(cth, 0, 100);
189 
190  // Compute base damage done with the weapon.
191  int base_damage = weapon->modified_damage(backstab_pos);
192 
193  // Get the damage multiplier applied to the base damage of the weapon.
194  int damage_multiplier = 100;
195 
196  // Time of day bonus.
197  damage_multiplier += combat_modifier(
198  resources::gameboard->units(), resources::gameboard->map(), u_loc, u.alignment(), u.is_fearless());
199 
200  // Leadership bonus.
201  int leader_bonus = under_leadership(u, u_loc, weapon, opp_weapon);
202  if(leader_bonus != 0) {
203  damage_multiplier += leader_bonus;
204  }
205 
206  // Resistance modifier.
207  damage_multiplier *= opp.damage_from(*weapon, !attacking, opp_loc, opp_weapon);
208 
209  // Compute both the normal and slowed damage.
210  damage = round_damage(base_damage, damage_multiplier, 10000);
211  slow_damage = round_damage(base_damage, damage_multiplier, 20000);
212 
213  if(is_slowed) {
215  }
216 
217  // Compute drain amounts only if draining is possible.
218  if(drains) {
219  unit_ability_list drain_specials = weapon->get_special_ability("drains");
220  // Compute the drain percent (with 50% as the base for backward compatibility)
221  unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos);
222  drain_percent = drain_percent_effects.get_composite_value();
223  }
224 
225  // Add heal_on_hit (the drain constant)
226  unit_ability_list heal_on_hit_specials = weapon->get_special_ability("heal_on_hit");
227  unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos);
228  drain_constant += heal_on_hit_effects.get_composite_value();
229 
231 
232  // Compute the number of blows and handle swarm.
233  weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
236 }
237 
239  const_attack_ptr att_weapon,
240  bool attacking,
241  const unit_type* opp_type,
242  const_attack_ptr opp_weapon,
243  unsigned int opp_terrain_defense,
244  int lawful_bonus)
245  : weapon(att_weapon)
246  , attack_num(-2) // This is and stays invalid. Always use weapon when using this constructor.
247  , is_attacker(attacking)
248  , is_poisoned(false)
249  , is_slowed(false)
250  , slows(false)
251  , drains(false)
252  , petrifies(false)
253  , plagues(false)
254  , poisons(false)
255  , backstab_pos(false)
256  , swarm(false)
257  , firststrike(false)
258  , disable(false)
259  , experience(0)
260  , max_experience(0)
261  , level(0)
262  , rounds(1)
263  , hp(0)
264  , max_hp(0)
265  , chance_to_hit(0)
266  , damage(0)
267  , slow_damage(0)
268  , drain_percent(0)
269  , drain_constant(0)
270  , num_blows(0)
271  , swarm_min(0)
272  , swarm_max(0)
273  , plague_type()
274 {
275  if(!u_type || !opp_type) {
276  return;
277  }
278 
279  // Get the current state of the unit.
280  if(u_type->hitpoints() < 0) {
281  hp = 0;
282  } else {
283  hp = u_type->hitpoints();
284  }
285 
286  max_experience = u_type->experience_needed();
287  level = (u_type->level());
288  max_hp = (u_type->hitpoints());
289 
290  // Exit if no weapon.
291  if(!weapon) {
292  return;
293  }
294 
295  // Get the weapon characteristics as appropriate.
296  auto ctx = weapon->specials_context(*u_type, map_location::null_location(), attacking);
297  boost::optional<decltype(ctx)> opp_ctx;
298 
299  if(opp_weapon) {
300  opp_ctx.emplace(opp_weapon->specials_context(*opp_type, map_location::null_location(), !attacking));
301  }
302 
303  slows = weapon->get_special_bool("slow");
304  drains = !opp_type->musthave_status("undrainable") && weapon->get_special_bool("drains");
305  petrifies = weapon->get_special_bool("petrifies");
306  poisons = !opp_type->musthave_status("unpoisonable") && weapon->get_special_bool("poison");
307  rounds = weapon->get_specials("berserk").highest("value", 1).first;
308  firststrike = weapon->get_special_bool("firststrike");
309  disable = weapon->get_special_bool("disable");
310 
311  unit_ability_list plague_specials = weapon->get_specials("plague");
312  plagues = !opp_type->musthave_status("unplagueable") && !plague_specials.empty() &&
313  opp_type->undead_variation() != "null";
314 
315  if(plagues) {
316  plague_type = (*plague_specials.front().first)["type"].str();
317  if(plague_type.empty()) {
318  plague_type = u_type->base_id();
319  }
320  }
321 
322  signed int cth = 100 - opp_terrain_defense + weapon->accuracy() - (opp_weapon ? opp_weapon->parry() : 0);
323  cth = utils::clamp(cth, 0, 100);
324 
325  unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
326  unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos);
327  cth = cth_effects.get_composite_value();
328 
329  chance_to_hit = utils::clamp(cth, 0, 100);
330 
331  int base_damage = weapon->modified_damage(backstab_pos);
332  int damage_multiplier = 100;
333  damage_multiplier
334  += generic_combat_modifier(lawful_bonus, u_type->alignment(), u_type->musthave_status("fearless"), 0);
335  damage_multiplier *= opp_type->resistance_against(weapon->type(), !attacking);
336 
337  damage = round_damage(base_damage, damage_multiplier, 10000);
338  slow_damage = round_damage(base_damage, damage_multiplier, 20000);
339 
340  if(drains) {
341  unit_ability_list drain_specials = weapon->get_specials("drains");
342 
343  // Compute the drain percent (with 50% as the base for backward compatibility)
344  unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos);
345  drain_percent = drain_percent_effects.get_composite_value();
346  }
347 
348  // Add heal_on_hit (the drain constant)
349  unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit");
350  unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos);
351  drain_constant += heal_on_hit_effects.get_composite_value();
352 
354 
355  // Compute the number of blows and handle swarm.
356  weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
359 }
360 
361 
362 // ==================================================================================
363 // BATTLE CONTEXT
364 // ==================================================================================
365 
367  const unit& attacker,
368  const map_location& a_loc,
369  int a_wep_index,
370  const unit& defender,
371  const map_location& d_loc,
372  int d_wep_index,
373  const unit_map& units)
374  : attacker_stats_()
375  , defender_stats_()
376  , attacker_combatant_()
377  , defender_combatant_()
378 {
379  size_t a_wep_uindex = static_cast<size_t>(a_wep_index);
380  size_t d_wep_uindex = static_cast<size_t>(d_wep_index);
381 
382  const_attack_ptr a_wep(a_wep_uindex < attacker.attacks().size() ? attacker.attacks()[a_wep_index].shared_from_this() : nullptr);
383  const_attack_ptr d_wep(d_wep_uindex < defender.attacks().size() ? defender.attacks()[d_wep_index].shared_from_this() : nullptr);
384 
385  attacker_stats_.reset(new battle_context_unit_stats(attacker, a_loc, a_wep_index, true , defender, d_loc, d_wep, units));
386  defender_stats_.reset(new battle_context_unit_stats(defender, d_loc, d_wep_index, false, attacker, a_loc, a_wep, units));
387 }
388 
389 void battle_context::simulate(const combatant* prev_def)
390 {
391  assert((attacker_combatant_.get() != nullptr) == (defender_combatant_.get() != nullptr));
392  assert(attacker_stats_);
393  assert(defender_stats_);
394  if(!attacker_combatant_) {
396  defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
398  }
399 }
400 
401 // more like a factory method than a constructor, always calls one of the other constructors.
403  const map_location& attacker_loc,
404  const map_location& defender_loc,
405  int attacker_weapon,
406  int defender_weapon,
407  double aggression,
408  const combatant* prev_def,
409  const unit* attacker_ptr,
410  const unit* defender_ptr)
411  : attacker_stats_(nullptr)
412  , defender_stats_(nullptr)
413  , attacker_combatant_(nullptr)
414  , defender_combatant_(nullptr)
415 {
416  //TODO: maybe check before dereferencing units.find(attacker_loc),units.find(defender_loc) ?
417  const unit& attacker = attacker_ptr ? *attacker_ptr : *units.find(attacker_loc);
418  const unit& defender = defender_ptr ? *defender_ptr : *units.find(defender_loc);
419  const double harm_weight = 1.0 - aggression;
420 
421  if(attacker_weapon == -1) {
422  *this = choose_attacker_weapon(
423  attacker, defender, units, attacker_loc, defender_loc, harm_weight, prev_def
424  );
425  }
426  else if(defender_weapon == -1) {
427  *this = choose_defender_weapon(
428  attacker, defender, attacker_weapon, units, attacker_loc, defender_loc, prev_def
429  );
430  }
431  else {
432  *this = battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, defender_weapon, units);
433  }
434 
435  assert(attacker_stats_);
436  assert(defender_stats_);
437 }
438 
442  , attacker_combatant_(nullptr)
443  , defender_combatant_(nullptr)
444 {
445 }
446 
447 
448 /** @todo FIXME: better to initialize combatant initially (move into
449  battle_context_unit_stats?), just do fight() when required. */
451 {
452  // We calculate this lazily, since AI doesn't always need it.
453  simulate(prev_def);
454  return *attacker_combatant_;
455 }
456 
458 {
459  // We calculate this lazily, since AI doesn't always need it.
460  simulate(prev_def);
461  return *defender_combatant_;
462 }
463 
464 // Given this harm_weight, are we better than that other context?
465 bool battle_context::better_attack(class battle_context& that, double harm_weight)
466 {
467  return better_combat(
470  that.get_attacker_combatant(),
471  that.get_defender_combatant(),
472  harm_weight
473  );
474 }
475 
476 // Given this harm_weight, are we better than that other context?
477 bool battle_context::better_defense(class battle_context& that, double harm_weight)
478 {
479  return better_combat(
482  that.get_defender_combatant(),
483  that.get_attacker_combatant(),
484  harm_weight
485  );
486 }
487 
488 // Does combat A give us a better result than combat B?
490  const combatant& them_a,
491  const combatant& us_b,
492  const combatant& them_b,
493  double harm_weight)
494 {
495  double a, b;
496 
497  // Compare: P(we kill them) - P(they kill us).
498  a = them_a.hp_dist[0] - us_a.hp_dist[0] * harm_weight;
499  b = them_b.hp_dist[0] - us_b.hp_dist[0] * harm_weight;
500 
501  if(a - b < -0.01) {
502  return false;
503  }
504 
505  if(a - b > 0.01) {
506  return true;
507  }
508 
509  // Add poison to calculations
510  double poison_a_us = (us_a.poisoned) * game_config::poison_amount;
511  double poison_a_them = (them_a.poisoned) * game_config::poison_amount;
512  double poison_b_us = (us_b.poisoned) * game_config::poison_amount;
513  double poison_b_them = (them_b.poisoned) * game_config::poison_amount;
514 
515  // Compare: damage to them - damage to us (average_hp replaces -damage)
516  a = (us_a.average_hp() - poison_a_us) * harm_weight - (them_a.average_hp() - poison_a_them);
517  b = (us_b.average_hp() - poison_b_us) * harm_weight - (them_b.average_hp() - poison_b_them);
518 
519  if(a - b < -0.01) {
520  return false;
521  }
522 
523  if(a - b > 0.01) {
524  return true;
525  }
526 
527  // All else equal: go for most damage.
528  return them_a.average_hp() < them_b.average_hp();
529 }
530 
532  const unit& defender,
533  const unit_map& units,
534  const map_location& attacker_loc,
535  const map_location& defender_loc,
536  double harm_weight,
537  const combatant* prev_def)
538 {
539  log_scope2(log_attack, "choose_attacker_weapon");
540  std::vector<battle_context> choices;
541 
542  // What options does attacker have?
543  for(size_t i = 0; i < attacker.attacks().size(); ++i) {
544  const attack_type& att = attacker.attacks()[i];
545 
546  if(att.attack_weight() <= 0) {
547  continue;
548  }
549  battle_context bc = choose_defender_weapon(attacker, defender, i, units, attacker_loc, defender_loc, prev_def);
550  //choose_defender_weapon will always choose the weapon that disabels the attackers weapon if possible.
551  if(bc.attacker_stats_->disable) {
552  continue;
553  }
554  choices.emplace_back(std::move(bc));
555  }
556 
557  if(choices.empty()) {
558  return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
559  }
560 
561  if(choices.size() == 1) {
562  return std::move(choices[0]);
563  }
564 
565  // Multiple options: simulate them, save best.
566  battle_context* best_choice = nullptr;
567  for(auto& choice : choices) {
568  // If choose_defender_weapon didn't simulate, do so now.
569  choice.simulate(prev_def);
570 
571  if(!best_choice || choice.better_attack(*best_choice, harm_weight)) {
572  best_choice = &choice;
573  }
574  }
575 
576  if(best_choice) {
577  return std::move(*best_choice);
578  }
579  else {
580  return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
581  }
582 }
583 
584 /** @todo FIXME: Hand previous defender unit in here. */
586  const unit& defender,
587  unsigned attacker_weapon,
588  const unit_map& units,
589  const map_location& attacker_loc,
590  const map_location& defender_loc,
591  const combatant* prev_def)
592 {
593  log_scope2(log_attack, "choose_defender_weapon");
594  VALIDATE(attacker_weapon < attacker.attacks().size(), _("An invalid attacker weapon got selected."));
595 
596  const attack_type& att = attacker.attacks()[attacker_weapon];
597  auto no_weapon = [&]() { return battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, -1, units); };
598  std::vector<battle_context> choices;
599 
600  // What options does defender have?
601  for(size_t i = 0; i < defender.attacks().size(); ++i) {
602  const attack_type& def = defender.attacks()[i];
603  if(def.range() != att.range() || def.defense_weight() <= 0) {
604  //no need to calculate the battle_context here.
605  continue;
606  }
607  battle_context bc(attacker, attacker_loc, attacker_weapon, defender, defender_loc, i, units);
608 
609  if(bc.defender_stats_->disable) {
610  continue;
611  }
612  if(bc.attacker_stats_->disable) {
613  //the defenders attack disables the attakers attack: always choose this one.
614  return bc;
615  }
616  choices.emplace_back(std::move(bc));
617  }
618 
619  if(choices.empty()) {
620  return no_weapon();
621  }
622 
623  if(choices.size() == 1) {
624  //only one usable weapon, don't simulate
625  return std::move(choices[0]);
626  }
627 
628  // Multiple options:
629  // First pass : get the best weight and the minimum simple rating for this weight.
630  // simple rating = number of blows * damage per blows (resistance taken in account) * cth * weight
631  // Eligible attacks for defense should have a simple rating greater or equal to this weight.
632 
633  int min_rating = 0;
634  {
635  double max_weight = 0.0;
636 
637  for(const auto& choice : choices) {
638  const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
639 
640  if(def.defense_weight() >= max_weight) {
641  const battle_context_unit_stats& def_stats = *choice.defender_stats_;
642 
643  max_weight = def.defense_weight();
644  int rating = static_cast<int>(
645  def_stats.num_blows * def_stats.damage * def_stats.chance_to_hit * def.defense_weight());
646 
647  if(def.defense_weight() > max_weight || rating < min_rating) {
648  min_rating = rating;
649  }
650  }
651  }
652  }
653 
654  battle_context* best_choice = nullptr;
655  // Multiple options: simulate them, save best.
656  for(auto& choice : choices) {
657  const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
658 
659  choice.simulate(prev_def);
660 
661 
662  int simple_rating = static_cast<int>(
663  choice.defender_stats_->num_blows * choice.defender_stats_->damage * choice.defender_stats_->chance_to_hit * def.defense_weight());
664 
665  //FIXME: make sure there is no mostake in the better_combat call-
666  if(simple_rating >= min_rating && (!best_choice || choice.better_defense(*best_choice, 1.0))) {
667  best_choice = &choice;
668  }
669  }
670 
671  return best_choice ? std::move(*best_choice) : no_weapon();
672 }
673 
674 
675 // ==================================================================================
676 // HELPERS
677 // ==================================================================================
678 
679 namespace
680 {
681 void refresh_weapon_index(int& weap_index, const std::string& weap_id, attack_itors attacks)
682 {
683  // No attacks to choose from.
684  if(attacks.empty()) {
685  weap_index = -1;
686  return;
687  }
688 
689  // The currently selected attack fits.
690  if(weap_index >= 0 && weap_index < static_cast<int>(attacks.size()) && attacks[weap_index].id() == weap_id) {
691  return;
692  }
693 
694  // Look up the weapon by id.
695  if(!weap_id.empty()) {
696  for(int i = 0; i < static_cast<int>(attacks.size()); ++i) {
697  if(attacks[i].id() == weap_id) {
698  weap_index = i;
699  return;
700  }
701  }
702  }
703 
704  // Lookup has failed.
705  weap_index = -1;
706  return;
707 }
708 
709 /** Helper class for performing an attack. */
710 class attack
711 {
712 public:
713  attack(const map_location& attacker,
714  const map_location& defender,
715  int attack_with,
716  int defend_with,
717  bool update_display = true);
718 
719  void perform();
720 
721 private:
722  class attack_end_exception
723  {
724  };
725 
726  bool perform_hit(bool, statistics::attack_context&);
727  void fire_event(const std::string& n);
728  void refresh_bc();
729 
730  /** Structure holding unit info used in the attack action. */
731  struct unit_info
732  {
733  const map_location loc_;
734  int weapon_;
735  unit_map& units_;
736  std::size_t id_; /**< unit.underlying_id() */
737  std::string weap_id_;
738  int orig_attacks_;
739  int n_attacks_; /**< Number of attacks left. */
740  int cth_;
741  int damage_;
742  int xp_;
743 
744  unit_info(const map_location& loc, int weapon, unit_map& units);
745  unit& get_unit();
746  bool valid();
747 
748  std::string dump();
749  };
750 
751  /**
752  * Used in perform_hit to confirm a replay is in sync.
753  * Check OOS_error_ after this method, true if error detected.
754  */
755  void check_replay_attack_result(bool&, int, int&, config, unit_info&);
756 
757  void unit_killed(
758  unit_info&, unit_info&, const battle_context_unit_stats*&, const battle_context_unit_stats*&, bool);
759 
760  std::unique_ptr<battle_context> bc_;
761 
762  const battle_context_unit_stats* a_stats_;
763  const battle_context_unit_stats* d_stats_;
764 
765  int abs_n_attack_, abs_n_defend_;
766  // update_att_fog_ is not used, other than making some code simpler.
767  bool update_att_fog_, update_def_fog_, update_minimap_;
768 
769  unit_info a_, d_;
770  unit_map& units_;
771  std::ostringstream errbuf_;
772 
773  bool update_display_;
774  bool OOS_error_;
775 
776  bool use_prng_;
777 
778  std::vector<bool> prng_attacker_;
779  std::vector<bool> prng_defender_;
780 };
781 
782 attack::unit_info::unit_info(const map_location& loc, int weapon, unit_map& units)
783  : loc_(loc)
784  , weapon_(weapon)
785  , units_(units)
786  , id_()
787  , weap_id_()
788  , orig_attacks_(0)
789  , n_attacks_(0)
790  , cth_(0)
791  , damage_(0)
792  , xp_(0)
793 {
794  unit_map::iterator i = units_.find(loc_);
795  if(!i.valid()) {
796  return;
797  }
798 
799  id_ = i->underlying_id();
800 }
801 
802 unit& attack::unit_info::get_unit()
803 {
804  unit_map::iterator i = units_.find(loc_);
805  assert(i.valid() && i->underlying_id() == id_);
806  return *i;
807 }
808 
809 bool attack::unit_info::valid()
810 {
811  unit_map::iterator i = units_.find(loc_);
812  return i.valid() && i->underlying_id() == id_;
813 }
814 
815 std::string attack::unit_info::dump()
816 {
817  std::stringstream s;
818  s << get_unit().type_id() << " (" << loc_.wml_x() << ',' << loc_.wml_y() << ')';
819  return s.str();
820 }
821 
822 attack::attack(const map_location& attacker,
823  const map_location& defender,
824  int attack_with,
825  int defend_with,
826  bool update_display)
827  : bc_(nullptr)
828  , a_stats_(nullptr)
829  , d_stats_(nullptr)
830  , abs_n_attack_(0)
831  , abs_n_defend_(0)
832  , update_att_fog_(false)
833  , update_def_fog_(false)
834  , update_minimap_(false)
835  , a_(attacker, attack_with, resources::gameboard->units())
836  , d_(defender, defend_with, resources::gameboard->units())
837  , units_(resources::gameboard->units())
838  , errbuf_()
839  , update_display_(update_display)
840  , OOS_error_(false)
841 
842  //new experimental prng mode.
843  , use_prng_(preferences::get("use_prng") == "yes" && randomness::generator->is_networked() == false)
844 {
845  if(use_prng_) {
846  std::cerr << "Using experimental PRNG for combat\n";
847  }
848 }
849 
850 void attack::fire_event(const std::string& n)
851 {
852  LOG_NG << "attack: firing '" << n << "' event\n";
853 
854  // prepare the event data for weapon filtering
855  config ev_data;
856  config& a_weapon_cfg = ev_data.add_child("first");
857  config& d_weapon_cfg = ev_data.add_child("second");
858 
859  // Need these to ensure weapon filters work correctly
860  boost::optional<attack_type::specials_context_t> a_ctx, d_ctx;
861 
862  if(a_stats_->weapon != nullptr && a_.valid()) {
863  if(d_stats_->weapon != nullptr && d_.valid()) {
864  a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, nullptr, a_.loc_, d_.loc_, true, d_stats_->weapon));
865  } else {
866  a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, a_.loc_, true));
867  }
868  a_stats_->weapon->write(a_weapon_cfg);
869  }
870 
871  if(d_stats_->weapon != nullptr && d_.valid()) {
872  if(a_stats_->weapon != nullptr && a_.valid()) {
873  d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, nullptr, d_.loc_, a_.loc_, false, a_stats_->weapon));
874  } else {
875  d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, d_.loc_, false));
876  }
877  d_stats_->weapon->write(d_weapon_cfg);
878  }
879 
880  if(a_weapon_cfg["name"].empty()) {
881  a_weapon_cfg["name"] = "none";
882  }
883 
884  if(d_weapon_cfg["name"].empty()) {
885  d_weapon_cfg["name"] = "none";
886  }
887 
888  if(n == "attack_end") {
889  // We want to fire attack_end event in any case! Even if one of units was removed by WML.
890  resources::game_events->pump().fire(n, a_.loc_, d_.loc_, ev_data);
891  return;
892  }
893 
894  // damage_inflicted is set in these two events.
895  // TODO: should we set this value from unit_info::damage, or continue using the WML variable?
896  if(n == "attacker_hits" || n == "defender_hits") {
897  ev_data["damage_inflicted"] = resources::gamedata->get_variable("damage_inflicted");
898  }
899 
900  const int defender_side = d_.get_unit().side();
901 
902  bool wml_aborted;
903  std::tie(std::ignore, wml_aborted) = resources::game_events->pump().fire(n,
905  game_events::entity_location(d_.loc_, d_.id_), ev_data);
906 
907  // The event could have killed either the attacker or
908  // defender, so we have to make sure they still exist.
909  refresh_bc();
910 
911  if(wml_aborted || !a_.valid() || !d_.valid()
912  || !resources::gameboard->get_team(a_.get_unit().side()).is_enemy(d_.get_unit().side())
913  ) {
914  actions::recalculate_fog(defender_side);
915 
916  if(update_display_) {
918  }
919 
920  fire_event("attack_end");
921  throw attack_end_exception();
922  }
923 }
924 
925 void attack::refresh_bc()
926 {
927  // Fix index of weapons.
928  if(a_.valid()) {
929  refresh_weapon_index(a_.weapon_, a_.weap_id_, a_.get_unit().attacks());
930  }
931 
932  if(d_.valid()) {
933  refresh_weapon_index(d_.weapon_, d_.weap_id_, d_.get_unit().attacks());
934  }
935 
936  if(!a_.valid() || !d_.valid()) {
937  // Fix pointer to weapons.
938  const_cast<battle_context_unit_stats*>(a_stats_)->weapon
939  = a_.valid() && a_.weapon_ >= 0 ? a_.get_unit().attacks()[a_.weapon_].shared_from_this() : nullptr;
940 
941  const_cast<battle_context_unit_stats*>(d_stats_)->weapon
942  = d_.valid() && d_.weapon_ >= 0 ? d_.get_unit().attacks()[d_.weapon_].shared_from_this() : nullptr;
943 
944  return;
945  }
946 
947  bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_));
948 
949  a_stats_ = &bc_->get_attacker_stats();
950  d_stats_ = &bc_->get_defender_stats();
951 
952  a_.cth_ = a_stats_->chance_to_hit;
953  d_.cth_ = d_stats_->chance_to_hit;
954  a_.damage_ = a_stats_->damage;
955  d_.damage_ = d_stats_->damage;
956 }
957 
958 bool attack::perform_hit(bool attacker_turn, statistics::attack_context& stats)
959 {
960  unit_info& attacker = attacker_turn ? a_ : d_;
961  unit_info& defender = attacker_turn ? d_ : a_;
962 
963  // NOTE: we need to use a reference-to-pointer here so a_stats_ and d_stats_ can be
964  // modified without. Using a pointer directly would render them invalid when that happened.
965  const battle_context_unit_stats*& attacker_stats = attacker_turn ? a_stats_ : d_stats_;
966  const battle_context_unit_stats*& defender_stats = attacker_turn ? d_stats_ : a_stats_;
967 
968  int& abs_n = attacker_turn ? abs_n_attack_ : abs_n_defend_;
969  bool& update_fog = attacker_turn ? update_def_fog_ : update_att_fog_;
970 
971  int ran_num;
972 
973  if(use_prng_) {
974 
975  std::vector<bool>& prng_seq = attacker_turn ? prng_attacker_ : prng_defender_;
976 
977  if(prng_seq.empty()) {
978  const int ntotal = attacker.cth_*attacker.n_attacks_;
979  int num_hits = ntotal/100;
980  const int additional_hit_chance = ntotal%100;
981  if(additional_hit_chance > 0 && randomness::generator->get_random_int(0, 99) < additional_hit_chance) {
982  ++num_hits;
983  }
984 
985  std::vector<int> indexes;
986  for(int i = 0; i != attacker.n_attacks_; ++i) {
987  prng_seq.push_back(false);
988  indexes.push_back(i);
989  }
990 
991  for(int i = 0; i != num_hits; ++i) {
992  int n = randomness::generator->get_random_int(0, static_cast<int>(indexes.size())-1);
993  prng_seq[indexes[n]] = true;
994  indexes.erase(indexes.begin() + n);
995  }
996  }
997 
998  bool does_hit = prng_seq.back();
999  prng_seq.pop_back();
1000  ran_num = does_hit ? 0 : 99;
1001  } else {
1002  ran_num = randomness::generator->get_random_int(0, 99);
1003  }
1004  bool hits = (ran_num < attacker.cth_);
1005 
1006  int damage = 0;
1007  if(hits) {
1008  damage = attacker.damage_;
1009  resources::gamedata->get_variable("damage_inflicted") = damage;
1010  }
1011 
1012  // Make sure that if we're serializing a game here,
1013  // we got the same results as the game did originally.
1014  const config local_results {"chance", attacker.cth_, "hits", hits, "damage", damage};
1015 
1016  config replay_results;
1017  bool equals_replay = checkup_instance->local_checkup(local_results, replay_results);
1018 
1019  if(!equals_replay) {
1020  check_replay_attack_result(hits, ran_num, damage, replay_results, attacker);
1021  }
1022 
1023  // can do no more damage than the defender has hitpoints
1024  int damage_done = std::min<int>(defender.get_unit().hitpoints(), attacker.damage_);
1025 
1026  // expected damage = damage potential * chance to hit (as a percentage)
1027  double expected_damage = damage_done * attacker.cth_ * 0.01;
1028 
1029  if(attacker_turn) {
1030  stats.attack_expected_damage(expected_damage, 0);
1031  } else {
1032  stats.attack_expected_damage(0, expected_damage);
1033  }
1034 
1035  int drains_damage = 0;
1036  if(hits && attacker_stats->drains) {
1037  drains_damage = damage_done * attacker_stats->drain_percent / 100 + attacker_stats->drain_constant;
1038 
1039  // don't drain so much that the attacker gets more than his maximum hitpoints
1040  drains_damage =
1041  std::min<int>(drains_damage, attacker.get_unit().max_hitpoints() - attacker.get_unit().hitpoints());
1042 
1043  // if drain is negative, don't allow drain to kill the attacker
1044  drains_damage = std::max<int>(drains_damage, 1 - attacker.get_unit().hitpoints());
1045  }
1046 
1047  if(update_display_) {
1048  std::ostringstream float_text;
1049  std::vector<std::string> extra_hit_sounds;
1050 
1051  if(hits) {
1052  const unit& defender_unit = defender.get_unit();
1053  if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
1054  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^poisoned") : _("poisoned"))
1055  << '\n';
1056 
1057  extra_hit_sounds.push_back(game_config::sounds::status::poisoned);
1058  }
1059 
1060  if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
1061  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^slowed") : _("slowed")) << '\n';
1062 
1063  extra_hit_sounds.push_back(game_config::sounds::status::slowed);
1064  }
1065 
1066  if(attacker_stats->petrifies) {
1067  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^petrified") : _("petrified"))
1068  << '\n';
1069 
1070  extra_hit_sounds.push_back(game_config::sounds::status::petrified);
1071  }
1072  }
1073 
1077  attacker.loc_, defender.loc_,
1078  damage,
1079  *attacker_stats->weapon, defender_stats->weapon,
1080  abs_n, float_text.str(), drains_damage, "",
1081  &extra_hit_sounds
1082  );
1083  }
1084 
1085  bool dies = defender.get_unit().take_hit(damage);
1086  LOG_NG << "defender took " << damage << (dies ? " and died\n" : "\n");
1087 
1088  if(attacker_turn) {
1089  stats.attack_result(hits
1090  ? (dies
1094  attacker.cth_, damage_done, drains_damage
1095  );
1096  } else {
1097  stats.defend_result(hits
1098  ? (dies
1102  attacker.cth_, damage_done, drains_damage
1103  );
1104  }
1105 
1106  replay_results.clear();
1107 
1108  // There was also a attribute cfg["unit_hit"] which was never used so i deleted.
1109  equals_replay = checkup_instance->local_checkup(config{"dies", dies}, replay_results);
1110 
1111  if(!equals_replay) {
1112  bool results_dies = replay_results["dies"].to_bool();
1113 
1114  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the "
1115  << (attacker_turn ? "defender" : "attacker") << ' ' << (results_dies ? "perished" : "survived")
1116  << " while in-game calculations show it " << (dies ? "perished" : "survived")
1117  << " (over-riding game calculations with data source results)\n";
1118 
1119  dies = results_dies;
1120 
1121  // Set hitpoints to 0 so later checks don't invalidate the death.
1122  if(results_dies) {
1123  defender.get_unit().set_hitpoints(0);
1124  }
1125 
1126  OOS_error_ = true;
1127  }
1128 
1129  if(hits) {
1130  try {
1131  fire_event(attacker_turn ? "attacker_hits" : "defender_hits");
1132  } catch(const attack_end_exception&) {
1133  refresh_bc();
1134  return false;
1135  }
1136  } else {
1137  try {
1138  fire_event(attacker_turn ? "attacker_misses" : "defender_misses");
1139  } catch(const attack_end_exception&) {
1140  refresh_bc();
1141  return false;
1142  }
1143  }
1144 
1145  refresh_bc();
1146 
1147  bool attacker_dies = false;
1148 
1149  if(drains_damage > 0) {
1150  attacker.get_unit().heal(drains_damage);
1151  } else if(drains_damage < 0) {
1152  attacker_dies = attacker.get_unit().take_hit(-drains_damage);
1153  }
1154 
1155  if(dies) {
1156  unit_killed(attacker, defender, attacker_stats, defender_stats, false);
1157  update_fog = true;
1158  }
1159 
1160  if(attacker_dies) {
1161  unit_killed(defender, attacker, defender_stats, attacker_stats, true);
1162  (attacker_turn ? update_att_fog_ : update_def_fog_) = true;
1163  }
1164 
1165  if(dies) {
1166  update_minimap_ = true;
1167  return false;
1168  }
1169 
1170  if(hits) {
1171  unit& defender_unit = defender.get_unit();
1172 
1173  if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
1174  defender_unit.set_state(unit::STATE_POISONED, true);
1175  LOG_NG << "defender poisoned\n";
1176  }
1177 
1178  if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
1179  defender_unit.set_state(unit::STATE_SLOWED, true);
1180  update_fog = true;
1181  defender.damage_ = defender_stats->slow_damage;
1182  LOG_NG << "defender slowed\n";
1183  }
1184 
1185  // If the defender is petrified, the fight stops immediately
1186  if(attacker_stats->petrifies) {
1187  defender_unit.set_state(unit::STATE_PETRIFIED, true);
1188  update_fog = true;
1189  attacker.n_attacks_ = 0;
1190  defender.n_attacks_ = -1; // Petrified.
1191  resources::game_events->pump().fire("petrified", defender.loc_, attacker.loc_);
1192  refresh_bc();
1193  }
1194  }
1195 
1196  // Delay until here so that poison and slow go through
1197  if(attacker_dies) {
1198  update_minimap_ = true;
1199  return false;
1200  }
1201 
1202  --attacker.n_attacks_;
1203  return true;
1204 }
1205 
1206 void attack::unit_killed(unit_info& attacker,
1207  unit_info& defender,
1208  const battle_context_unit_stats*& attacker_stats,
1209  const battle_context_unit_stats*& defender_stats,
1210  bool drain_killed)
1211 {
1212  attacker.xp_ = game_config::kill_xp(defender.get_unit().level());
1213  defender.xp_ = 0;
1214 
1215  display::get_singleton()->invalidate(attacker.loc_);
1216 
1217  game_events::entity_location death_loc(defender.loc_, defender.id_);
1218  game_events::entity_location attacker_loc(attacker.loc_, attacker.id_);
1219 
1220  std::string undead_variation = defender.get_unit().undead_variation();
1221 
1222  fire_event("attack_end");
1223  refresh_bc();
1224 
1225  // Get weapon info for last_breath and die events.
1226  config dat;
1227  config a_weapon_cfg = attacker_stats->weapon && attacker.valid() ? attacker_stats->weapon->to_config() : config();
1228  config d_weapon_cfg = defender_stats->weapon && defender.valid() ? defender_stats->weapon->to_config() : config();
1229 
1230  if(a_weapon_cfg["name"].empty()) {
1231  a_weapon_cfg["name"] = "none";
1232  }
1233 
1234  if(d_weapon_cfg["name"].empty()) {
1235  d_weapon_cfg["name"] = "none";
1236  }
1237 
1238  dat.add_child("first", d_weapon_cfg);
1239  dat.add_child("second", a_weapon_cfg);
1240 
1241  resources::game_events->pump().fire("last_breath", death_loc, attacker_loc, dat);
1242  refresh_bc();
1243 
1244  // WML has invalidated the dying unit, abort.
1245  if(!defender.valid() || defender.get_unit().hitpoints() > 0) {
1246  return;
1247  }
1248 
1249  if(!attacker.valid()) {
1251  defender.loc_,
1252  defender.get_unit(),
1253  nullptr,
1254  defender_stats->weapon
1255  );
1256  } else {
1258  defender.loc_,
1259  defender.get_unit(),
1260  attacker_stats->weapon,
1261  defender_stats->weapon,
1262  attacker.loc_,
1263  &attacker.get_unit()
1264  );
1265  }
1266 
1267  resources::game_events->pump().fire("die", death_loc, attacker_loc, dat);
1268  refresh_bc();
1269 
1270  if(!defender.valid() || defender.get_unit().hitpoints() > 0) {
1271  // WML has invalidated the dying unit, abort
1272  return;
1273  }
1274 
1275  units_.erase(defender.loc_);
1276  resources::whiteboard->on_kill_unit();
1277 
1278  // Plague units make new units on the target hex.
1279  if(attacker.valid() && attacker_stats->plagues && !drain_killed) {
1280  LOG_NG << "trying to reanimate " << attacker_stats->plague_type << '\n';
1281 
1282  if(const unit_type* reanimator = unit_types.find(attacker_stats->plague_type)) {
1283  LOG_NG << "found unit type:" << reanimator->id() << '\n';
1284 
1285  unit_ptr newunit = unit::create(*reanimator, attacker.get_unit().side(), true, unit_race::MALE);
1286  newunit->set_attacks(0);
1287  newunit->set_movement(0, true);
1288  newunit->set_facing(map_location::get_opposite_dir(attacker.get_unit().facing()));
1289 
1290  // Apply variation
1291  if(undead_variation != "null") {
1292  config mod;
1293  config& variation = mod.add_child("effect");
1294  variation["apply_to"] = "variation";
1295  variation["name"] = undead_variation;
1296  newunit->add_modification("variation", mod);
1297  newunit->heal_fully();
1298  }
1299 
1300  newunit->set_location(death_loc);
1301  units_.insert(newunit);
1302 
1303  game_events::entity_location reanim_loc(defender.loc_, newunit->underlying_id());
1304  resources::game_events->pump().fire("unit_placed", reanim_loc);
1305 
1306  preferences::encountered_units().insert(newunit->type_id());
1307 
1308  if(update_display_) {
1309  display::get_singleton()->invalidate(death_loc);
1310  }
1311  }
1312  } else {
1313  LOG_NG << "unit not reanimated\n";
1314  }
1315 }
1316 
1317 void attack::perform()
1318 {
1319  // Stop the user from issuing any commands while the units are fighting.
1320  const events::command_disabler disable_commands;
1321 
1322  if(!a_.valid() || !d_.valid()) {
1323  return;
1324  }
1325 
1326  // no attack weapon => stop here and don't attack
1327  if(a_.weapon_ < 0) {
1328  a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1);
1329  a_.get_unit().set_movement(-1, true);
1330  return;
1331  }
1332 
1333  if(a_.get_unit().attacks_left() <= 0) {
1334  LOG_NG << "attack::perform(): not enough ap.\n";
1335  return;
1336  }
1337 
1338  a_.get_unit().set_facing(a_.loc_.get_relative_dir(d_.loc_));
1339  d_.get_unit().set_facing(d_.loc_.get_relative_dir(a_.loc_));
1340 
1341  a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1);
1342 
1343  VALIDATE(a_.weapon_ < static_cast<int>(a_.get_unit().attacks().size()),
1344  _("An invalid attacker weapon got selected."));
1345 
1346  a_.get_unit().set_movement(a_.get_unit().movement_left() - a_.get_unit().attacks()[a_.weapon_].movement_used(), true);
1347  a_.get_unit().set_state(unit::STATE_NOT_MOVED, false);
1348  a_.get_unit().set_resting(false);
1349  d_.get_unit().set_resting(false);
1350 
1351  // If the attacker was invisible, she isn't anymore!
1352  a_.get_unit().set_state(unit::STATE_UNCOVERED, true);
1353 
1354  bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_));
1355 
1356  a_stats_ = &bc_->get_attacker_stats();
1357  d_stats_ = &bc_->get_defender_stats();
1358 
1359  if(a_stats_->disable) {
1360  LOG_NG << "attack::perform(): tried to attack with a disabled attack.\n";
1361  return;
1362  }
1363 
1364  if(a_stats_->weapon) {
1365  a_.weap_id_ = a_stats_->weapon->id();
1366  }
1367 
1368  if(d_stats_->weapon) {
1369  d_.weap_id_ = d_stats_->weapon->id();
1370  }
1371 
1372  try {
1373  fire_event("attack");
1374  } catch(const attack_end_exception&) {
1375  return;
1376  }
1377 
1378  refresh_bc();
1379 
1380  DBG_NG << "getting attack statistics\n";
1381  statistics::attack_context attack_stats(
1382  a_.get_unit(), d_.get_unit(), a_stats_->chance_to_hit, d_stats_->chance_to_hit);
1383 
1384  a_.orig_attacks_ = a_stats_->num_blows;
1385  d_.orig_attacks_ = d_stats_->num_blows;
1386  a_.n_attacks_ = a_.orig_attacks_;
1387  d_.n_attacks_ = d_.orig_attacks_;
1388  a_.xp_ = game_config::combat_xp(d_.get_unit().level());
1389  d_.xp_ = game_config::combat_xp(a_.get_unit().level());
1390 
1391  bool defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
1392  unsigned int rounds = std::max<unsigned int>(a_stats_->rounds, d_stats_->rounds) - 1;
1393  const int defender_side = d_.get_unit().side();
1394 
1395  LOG_NG << "Fight: (" << a_.loc_ << ") vs (" << d_.loc_ << ") ATT: " << a_stats_->weapon->name() << " "
1396  << a_stats_->damage << "-" << a_stats_->num_blows << "(" << a_stats_->chance_to_hit
1397  << "%) vs DEF: " << (d_stats_->weapon ? d_stats_->weapon->name() : "none") << " " << d_stats_->damage << "-"
1398  << d_stats_->num_blows << "(" << d_stats_->chance_to_hit << "%)"
1399  << (defender_strikes_first ? " defender first-strike" : "") << "\n";
1400 
1401  // Play the pre-fight animation
1402  unit_display::unit_draw_weapon(a_.loc_, a_.get_unit(), a_stats_->weapon, d_stats_->weapon, d_.loc_, &d_.get_unit());
1403 
1404  for(;;) {
1405  DBG_NG << "start of attack loop...\n";
1406  ++abs_n_attack_;
1407 
1408  if(a_.n_attacks_ > 0 && !defender_strikes_first) {
1409  if(!perform_hit(true, attack_stats)) {
1410  DBG_NG << "broke from attack loop on attacker turn\n";
1411  break;
1412  }
1413  }
1414 
1415  // If the defender got to strike first, they use it up here.
1416  defender_strikes_first = false;
1417  ++abs_n_defend_;
1418 
1419  if(d_.n_attacks_ > 0) {
1420  if(!perform_hit(false, attack_stats)) {
1421  DBG_NG << "broke from attack loop on defender turn\n";
1422  break;
1423  }
1424  }
1425 
1426  // Continue the fight to death; if one of the units got petrified,
1427  // either n_attacks or n_defends is -1
1428  if(rounds > 0 && d_.n_attacks_ == 0 && a_.n_attacks_ == 0) {
1429  a_.n_attacks_ = a_.orig_attacks_;
1430  d_.n_attacks_ = d_.orig_attacks_;
1431  --rounds;
1432  defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
1433  }
1434 
1435  if(a_.n_attacks_ <= 0 && d_.n_attacks_ <= 0) {
1436  fire_event("attack_end");
1437  refresh_bc();
1438  break;
1439  }
1440  }
1441 
1442  // Set by attacker_hits and defender_hits events.
1443  resources::gamedata->clear_variable("damage_inflicted");
1444 
1445  if(update_def_fog_) {
1446  actions::recalculate_fog(defender_side);
1447  }
1448 
1449  // TODO: if we knew the viewing team, we could skip this display update
1450  if(update_minimap_ && update_display_) {
1452  }
1453 
1454  if(a_.valid()) {
1455  unit& u = a_.get_unit();
1456  u.anim_comp().set_standing();
1457  u.set_experience(u.experience() + a_.xp_);
1458  }
1459 
1460  if(d_.valid()) {
1461  unit& u = d_.get_unit();
1462  u.anim_comp().set_standing();
1463  u.set_experience(u.experience() + d_.xp_);
1464  }
1465 
1466  unit_display::unit_sheath_weapon(a_.loc_, a_.valid() ? &a_.get_unit() : nullptr, a_stats_->weapon, d_stats_->weapon,
1467  d_.loc_, d_.valid() ? &d_.get_unit() : nullptr);
1468 
1469  if(update_display_) {
1472  display::get_singleton()->invalidate(d_.loc_);
1473  }
1474 
1475  if(OOS_error_) {
1476  replay::process_error(errbuf_.str());
1477  }
1478 }
1479 
1480 void attack::check_replay_attack_result(
1481  bool& hits, int ran_num, int& damage, config replay_results, unit_info& attacker)
1482 {
1483  int results_chance = replay_results["chance"];
1484  bool results_hits = replay_results["hits"].to_bool();
1485  int results_damage = replay_results["damage"];
1486 
1487 #if 0
1488  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
1489  << " replay data differs from local calculated data:"
1490  << " chance to hit in data source: " << results_chance
1491  << " chance to hit in calculated: " << attacker.cth_
1492  << " chance to hit in data source: " << results_chance
1493  << " chance to hit in calculated: " << attacker.cth_
1494  ;
1495 
1496  attacker.cth_ = results_chance;
1497  hits = results_hits;
1498  damage = results_damage;
1499 
1500  OOS_error_ = true;
1501 #endif
1502 
1503  if(results_chance != attacker.cth_) {
1504  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
1505  << ": chance to hit is inconsistent. Data source: " << results_chance
1506  << "; Calculation: " << attacker.cth_ << " (over-riding game calculations with data source results)\n";
1507  attacker.cth_ = results_chance;
1508  OOS_error_ = true;
1509  }
1510 
1511  if(results_hits != hits) {
1512  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit was "
1513  << (results_hits ? "successful" : "unsuccessful") << ", while in-game calculations say the hit was "
1514  << (hits ? "successful" : "unsuccessful") << " random number: " << ran_num << " = " << (ran_num % 100)
1515  << "/" << results_chance << " (over-riding game calculations with data source results)\n";
1516  hits = results_hits;
1517  OOS_error_ = true;
1518  }
1519 
1520  if(results_damage != damage) {
1521  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit did "
1522  << results_damage << " damage, while in-game calculations show the hit doing " << damage
1523  << " damage (over-riding game calculations with data source results)\n";
1524  damage = results_damage;
1525  OOS_error_ = true;
1526  }
1527 }
1528 } // end anonymous namespace
1529 
1530 
1531 // ==================================================================================
1532 // FREE-STANDING FUNCTIONS
1533 // ==================================================================================
1534 
1535 void attack_unit(const map_location& attacker,
1536  const map_location& defender,
1537  int attack_with,
1538  int defend_with,
1539  bool update_display)
1540 {
1541  attack dummy(attacker, defender, attack_with, defend_with, update_display);
1542  dummy.perform();
1543 }
1544 
1546  const map_location& defender,
1547  int attack_with,
1548  int defend_with,
1549  bool update_display)
1550 {
1551  attack_unit(attacker, defender, attack_with, defend_with, update_display);
1552 
1554  if(atku != resources::gameboard->units().end()) {
1556  }
1557 
1559  if(defu != resources::gameboard->units().end()) {
1561  }
1562 }
1563 
1564 int under_leadership(const unit &u, const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon)
1565 {
1566  unit_ability_list abil = u.get_abilities("leadership", loc);
1567  for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
1568  if((!u.ability_affects_weapon(*i->first, weapon, false) || !u.ability_affects_weapon(*i->first, opp_weapon, true))) {
1569  i = abil.erase(i);
1570  } else {
1571  ++i;
1572  }
1573  }
1574  unit_abilities::effect leader_effect(abil, 0, false);
1575  return leader_effect.get_composite_value();
1576 }
1577 
1578 int combat_modifier(const unit_map& units,
1579  const gamemap& map,
1580  const map_location& loc,
1581  unit_type::ALIGNMENT alignment,
1582  bool is_fearless)
1583 {
1584  const tod_manager& tod_m = *resources::tod_manager;
1585  const time_of_day& effective_tod = tod_m.get_illuminated_time_of_day(units, map, loc);
1586  return combat_modifier(effective_tod, alignment, is_fearless);
1587 }
1588 
1589 int combat_modifier(const time_of_day& effective_tod,
1590  unit_type::ALIGNMENT alignment,
1591  bool is_fearless)
1592 {
1593  const tod_manager& tod_m = *resources::tod_manager;
1594  const int lawful_bonus = effective_tod.lawful_bonus;
1595  return generic_combat_modifier(lawful_bonus, alignment, is_fearless, tod_m.get_max_liminal_bonus());
1596 }
1597 
1598 int generic_combat_modifier(int lawful_bonus, unit_type::ALIGNMENT alignment, bool is_fearless, int max_liminal_bonus)
1599 {
1600  int bonus;
1601 
1602  switch(alignment.v) {
1603  case unit_type::ALIGNMENT::LAWFUL:
1604  bonus = lawful_bonus;
1605  break;
1606  case unit_type::ALIGNMENT::NEUTRAL:
1607  bonus = 0;
1608  break;
1609  case unit_type::ALIGNMENT::CHAOTIC:
1610  bonus = -lawful_bonus;
1611  break;
1612  case unit_type::ALIGNMENT::LIMINAL:
1613  bonus = std::max(0, max_liminal_bonus-std::abs(lawful_bonus));
1614  break;
1615  default:
1616  bonus = 0;
1617  }
1618 
1619  if(is_fearless) {
1620  bonus = std::max<int>(bonus, 0);
1621  }
1622 
1623  return bonus;
1624 }
1625 
1626 bool backstab_check(const map_location& attacker_loc,
1627  const map_location& defender_loc,
1628  const unit_map& units,
1629  const std::vector<team>& teams)
1630 {
1631  const unit_map::const_iterator defender = units.find(defender_loc);
1632  if(defender == units.end()) {
1633  return false; // No defender
1634  }
1635 
1637  get_adjacent_tiles(defender_loc, adj.data());
1638 
1639  unsigned i;
1640 
1641  for(i = 0; i < adj.size(); ++i) {
1642  if(adj[i] == attacker_loc) {
1643  break;
1644  }
1645  }
1646 
1647  if(i >= 6) {
1648  return false; // Attack not from adjacent location
1649  }
1650 
1651  const unit_map::const_iterator opp = units.find(adj[(i + 3) % 6]);
1652 
1653  // No opposite unit.
1654  if(opp == units.end()) {
1655  return false;
1656  }
1657 
1658  if(opp->incapacitated()) {
1659  return false;
1660  }
1661 
1662  // If sides aren't valid teams, then they are enemies.
1663  if(std::size_t(defender->side() - 1) >= teams.size() || std::size_t(opp->side() - 1) >= teams.size()) {
1664  return true;
1665  }
1666 
1667  // Defender and opposite are enemies.
1668  if(teams[defender->side() - 1].is_enemy(opp->side())) {
1669  return true;
1670  }
1671 
1672  // Defender and opposite are friends.
1673  return false;
1674 }
const_attack_ptr weapon
The weapon used by the unit to attack the opponent, or nullptr if there is none.
Definition: attack.hpp:50
constexpr const T & clamp(const T &value, const T &min, const T &max)
Definition: general.hpp:31
int kill_xp(int level)
Definition: game_config.hpp:46
void set_experience(int xp)
Sets the current experience point amount.
Definition: unit.hpp:527
std::unique_ptr< combatant > attacker_combatant_
Outcome of simulated fight.
Definition: attack.hpp:256
bool ability_affects_weapon(const config &cfg, const_attack_ptr weapon, bool is_opp) const
filters the weapons that condition the use of abilities for combat ([resistance],[leadership] or abil...
Definition: abilities.cpp:442
const std::string & base_id() const
The id of the original type from which this (variation) descended.
Definition: types.hpp:136
unsigned int calc_blows(unsigned new_hp) const
Calculates the number of blows we would have if we had new_hp.
Definition: attack.hpp:108
int combat_xp(int level)
Definition: game_config.hpp:51
#define LOG_NG
Definition: attack.cpp:57
bool empty() const
Definition: unit.hpp:78
static lg::log_domain log_attack("engine/attack")
::tod_manager * tod_manager
Definition: resources.cpp:29
int get_max_liminal_bonus() const
unit_iterator end()
Definition: map.hpp:415
std::vector< double > hp_dist
Resulting probability distribution (might be not as large as max_hp)
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:88
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:1208
void get_adjacent_tiles(const map_location &a, map_location *res)
Function which, given a location, will place all adjacent locations in res.
Definition: location.cpp:474
virtual const unit_map & units() const override
Definition: game_board.hpp:114
bool invalidate(const map_location &loc)
Function to invalidate a specific tile for redrawing.
Definition: display.cpp:3025
void unit_draw_weapon(const map_location &loc, unit &attacker, const_attack_ptr attack, const_attack_ptr secondary_attack, const map_location &defender_loc, unit *defender)
Play a pre-fight animation First unit is the attacker, second unit the defender.
Definition: udisplay.cpp:524
std::string plague_type
The plague type used by the attack, if any.
Definition: attack.hpp:82
static lg::log_domain log_config("config")
This class represents a single unit of a specific type.
Definition: unit.hpp:106
int dummy
Definition: lstrlib.cpp:1125
boost::iterator_range< boost::indirect_iterator< attack_list::iterator > > attack_itors
unsigned int hp
Hitpoints of the unit at the beginning of the battle.
Definition: attack.hpp:71
Various functions implementing vision (through fog of war and shroud).
The unit is uncovered - it was hiding but has been spotted.
Definition: unit.hpp:841
iterator erase(const iterator &erase_it)
Definition: unit.hpp:84
Various functions that implement attacks and attack calculations.
bool get_state(const std::string &state) const
Check if the unit is affected by a status effect.
Definition: unit.cpp:1355
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
static bool better_combat(const combatant &us_a, const combatant &them_a, const combatant &us_b, const combatant &them_b, double harm_weight)
Definition: attack.cpp:489
unit_race::GENDER gender() const
The gender of this unit.
Definition: unit.hpp:439
const combatant & get_attacker_combatant(const combatant *prev_def=nullptr)
Get the simulation results.
Definition: attack.cpp:450
#define a
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:473
double average_hp(unsigned int healing=0) const
What&#39;s the average hp (weighted average of hp_dist).
int under_leadership(const unit &u, const map_location &loc, const_attack_ptr weapon, const_attack_ptr opp_weapon)
Tests if the unit at loc is currently affected by leadership.
Definition: attack.cpp:1564
void invalidate_unit()
Function to invalidate that unit status displayed on the sidebar.
virtual const gamemap & map() const override
Definition: game_board.hpp:109
int lawful_bonus
The % bonus lawful units receive.
Definition: time_of_day.hpp:84
int wml_x() const
Definition: location.hpp:157
The unit is poisoned - it loses health each turn.
Definition: unit.hpp:839
int experience_needed(bool with_acceleration=true) const
Definition: types.cpp:541
unit_type_data unit_types
Definition: types.cpp:1433
The unit is petrified - it cannot move or be attacked.
Definition: unit.hpp:840
int resistance_against(const std::string &damage_name, bool attacker) const
Gets resistance while considering custom WML abilities.
Definition: types.cpp:784
bool is_slowed
True if the unit is slowed at the beginning of the battle.
Definition: attack.hpp:54
void insert(config_key_type key, T &&value)
Returns a reference to the first child with the given key.
Definition: config.hpp:437
Replay control code.
bool slows
Attack slows opponent when it hits.
Definition: attack.hpp:55
void clear()
Definition: config.cpp:863
int generic_combat_modifier(int lawful_bonus, unit_type::ALIGNMENT alignment, bool is_fearless, int max_liminal_bonus)
Returns the amount that a unit&#39;s damage should be multiplied by due to a given lawful_bonus.
Definition: attack.cpp:1598
int drain_constant
Base HP drained regardless of damage dealt.
Definition: attack.hpp:77
-file sdl_utils.hpp
unit_ability & front()
Definition: unit.hpp:79
void redraw_minimap()
Schedule the minimap to be redrawn.
Definition: display.hpp:622
unit_type::ALIGNMENT alignment() const
The alignment of this unit.
Definition: unit.hpp:449
unsigned int chance_to_hit
Effective chance to hit as a percentage (all factors accounted for).
Definition: attack.hpp:73
static unit_ptr create(const config &cfg, bool use_traits=false, const vconfig *vcfg=nullptr)
Initializes a unit from a config.
Definition: unit.hpp:162
A single unit type that the player may recruit.
Definition: types.hpp:42
game_data * gamedata
Definition: resources.cpp:22
config::attribute_value & get_variable(const std::string &varname)
throws invalid_variablename_exception if varname is no valid variable name.
Definition: game_data.cpp:62
std::vector< unit_ability >::iterator iterator
Definition: unit.hpp:69
map_location loc_
#define b
const unit_type & type() const
This unit&#39;s type, accounting for gender and variation.
Definition: unit.hpp:323
bool poisons
Attack poisons opponent when it hits.
Definition: attack.hpp:59
const combatant & get_defender_combatant(const combatant *prev_def=nullptr)
Definition: attack.cpp:457
Object which defines a time of day with associated bonuses, image, sounds etc.
Definition: time_of_day.hpp:57
bool backstab_pos
True if the attacker is in position to backstab the defender (this is used to determine whether to ap...
Definition: attack.hpp:60
int defense_modifier(const t_translation::terrain_code &terrain) const
The unit&#39;s defense on a given terrain.
Definition: unit.cpp:1649
bool musthave_status(const std::string &status) const
Definition: types.cpp:636
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:91
team & get_team(int i)
Definition: game_board.hpp:104
std::string get(const std::string &key)
Definition: general.cpp:228
int damage
Effective damage of the weapon (all factors accounted for).
Definition: attack.hpp:74
Various functions that implement advancements of units.
int damage_from(const attack_type &attack, bool attacker, const map_location &loc, const_attack_ptr weapon=nullptr) const
Calculates the damage this unit would take from a certain attack.
Definition: unit.hpp:947
void set_state(const std::string &state, bool value)
Set whether the unit is affected by a status effect.
Definition: unit.cpp:1403
#define VALIDATE(cond, message)
The macro to use for the validation of WML.
bool better_defense(class battle_context &that, double harm_weight)
Given this harm_weight, is this attack better than that?
Definition: attack.cpp:477
unsigned int level
Definition: attack.hpp:68
void attack_result(hit_result res, int cth, int damage, int drain)
Definition: statistics.cpp:573
The unit is slowed - it moves slower and does less damage.
Definition: unit.hpp:838
unsigned int rounds
Berserk special can force us to fight more than one round.
Definition: attack.hpp:70
unsigned int swarm_min
Minimum number of blows with swarm (equal to num_blows if swarm isn&#39;t used).
Definition: attack.hpp:79
int wml_y() const
Definition: location.hpp:158
static battle_context choose_attacker_weapon(const unit &attacker, const unit &defender, const unit_map &units, const map_location &attacker_loc, const map_location &defender_loc, double harm_weight, const combatant *prev_def)
Definition: attack.cpp:531
game_board * gameboard
Definition: resources.cpp:20
std::unique_ptr< battle_context_unit_stats > defender_stats_
Definition: attack.hpp:253
bool plagues
Attack turns opponent into a zombie when fatal.
Definition: attack.hpp:58
void unit_die(const map_location &loc, unit &loser, const_attack_ptr attack, const_attack_ptr secondary_attack, const map_location &winner_loc, unit *winner)
Show a unit fading out.
Definition: udisplay.cpp:572
bool better_attack(class battle_context &that, double harm_weight)
Given this harm_weight, is this attack better than that?
Definition: attack.cpp:465
Encapsulates the map of the game.
Definition: map.hpp:36
void recalculate_fog(int side)
Function that recalculates the fog of war.
Definition: vision.cpp:705
Computes the statistics of a battle between an attacker and a defender unit.
Definition: attack.hpp:171
const std::string & range() const
Definition: attack_type.hpp:44
checkup * checkup_instance
#define log_scope2(domain, description)
Definition: log.hpp:187
int attack_num
Index into unit->attacks() or -1 for none.
Definition: attack.hpp:51
Structure describing the statistics of a unit involved in the battle.
Definition: attack.hpp:48
The unit has not moved.
Definition: unit.hpp:842
std::array< map_location, 6 > adjacent_loc_array_t
Definition: location.hpp:170
std::unique_ptr< battle_context_unit_stats > attacker_stats_
Statistics of the units.
Definition: attack.hpp:252
game_events::manager * game_events
Definition: resources.cpp:24
advances the unit at loc if it has enough experience, maximum 20 times.
Definition: advancement.hpp:37
Encapsulates the map of the game.
Definition: location.hpp:42
int round_damage(int base_damage, int bonus, int divisor)
round (base_damage * bonus / divisor) to the closest integer, but up or down towards base_damage ...
Definition: math.hpp:79
unit_iterator find(std::size_t id)
Definition: map.cpp:311
std::shared_ptr< wb::manager > whiteboard
Definition: resources.cpp:33
static void process_error(const std::string &msg)
Definition: replay.cpp:195
All combat-related info.
const std::string & undead_variation() const
Info on the type of unit that the unit reanimates as.
Definition: types.hpp:124
const time_of_day get_illuminated_time_of_day(const unit_map &units, const gamemap &map, const map_location &loc, int for_turn=0) const
Returns time of day object for the passed turn at a location.
bool backstab_check(const map_location &attacker_loc, const map_location &defender_loc, const unit_map &units, const std::vector< team > &teams)
Function to check if an attack will satisfy the requirements for backstab.
Definition: attack.cpp:1626
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.
bool swarm
Attack has swarm special.
Definition: attack.hpp:64
int slow_damage
Effective damage if unit becomes slowed (== damage, if already slowed)
Definition: attack.hpp:75
std::size_t i
Definition: function.cpp:933
unit_animation_component & anim_comp() const
Definition: unit.hpp:1507
std::unique_ptr< combatant > defender_combatant_
Definition: attack.hpp:257
void unit_sheath_weapon(const map_location &primary_loc, unit *primary_unit, const_attack_ptr primary_attack, const_attack_ptr secondary_attack, const map_location &secondary_loc, unit *secondary_unit)
Play a post-fight animation Both unit can be set to null, only valid units will play their animation...
Definition: udisplay.cpp:542
int max_hitpoints() const
The max number of hitpoints this unit can have.
Definition: unit.hpp:479
void attack_unit_and_advance(const map_location &attacker, const map_location &defender, int attack_with, int defend_with, bool update_display)
Performs an attack, and advanced the units afterwards.
Definition: attack.cpp:1545
#define LOG_CF
Definition: attack.cpp:68
static map_location::DIRECTION s
unsigned int experience
Definition: attack.hpp:67
double attack_weight() const
Definition: attack_type.hpp:52
iterator begin()
Definition: unit.hpp:72
Define the game&#39;s event mechanism.
attack_itors attacks()
Gets an iterator over this unit&#39;s attacks.
Definition: unit.hpp:903
bool disable
Attack has disable special.
Definition: attack.hpp:66
bool firststrike
Attack has firststrike special.
Definition: attack.hpp:65
int get_composite_value() const
Definition: abilities.hpp:49
double defense_weight() const
Definition: attack_type.hpp:53
bool is_poisoned
True if the unit is poisoned at the beginning of the battle.
Definition: attack.hpp:53
int level() const
Definition: types.hpp:147
std::set< std::string > & encountered_units()
Definition: game.cpp:954
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
battle_context(const unit_map &units, const map_location &attacker_loc, const map_location &defender_loc, int attacker_weapon=-1, int defender_weapon=-1, double aggression=0.0, const combatant *prev_def=nullptr, const unit *attacker_ptr=nullptr, const unit *defender_ptr=nullptr)
If no attacker_weapon is given, we select the best one, based on harm_weight (1.0 means 1 hp lost cou...
Definition: attack.cpp:402
void advance_unit_at(const advance_unit_params &params)
int hitpoints() const
Definition: types.hpp:144
variant a_
Definition: function.cpp:722
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
config & add_child(config_key_type key)
Definition: config.cpp:476
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:486
int drain_percent
Percentage of damage recovered as health.
Definition: attack.hpp:76
const std::string & undead_variation() const
Definition: unit.hpp:557
static DIRECTION get_opposite_dir(DIRECTION d)
Definition: location.hpp:59
bool is_village(const map_location &loc) const
Definition: map.cpp:65
std::size_t distance_between(const map_location &a, const map_location &b)
Function which gives the number of hexes between two tiles (i.e.
Definition: location.cpp:557
static battle_context choose_defender_weapon(const unit &attacker, const unit &defender, unsigned attacker_weapon, const unit_map &units, const map_location &attacker_loc, const map_location &defender_loc, const combatant *prev_def)
Definition: attack.cpp:585
boost::intrusive_ptr< unit > unit_ptr
Definition: ptr.hpp:29
battle_context_unit_stats(const unit &u, const map_location &u_loc, int u_attack_num, bool attacking, const unit &opp, const map_location &opp_loc, const_attack_ptr opp_weapon, const unit_map &units)
Definition: attack.cpp:74
bool is_fearless() const
Gets whether this unit is fearless - ie, unaffected by time of day.
Definition: unit.hpp:1210
int experience() const
The current number of experience points this unit has.
Definition: unit.hpp:497
void attack_expected_damage(double attacker_inflict, double defender_inflict)
Definition: statistics.cpp:557
void attack_unit(const map_location &attacker, const map_location &defender, int attack_with, int defend_with, bool update_display)
Performs an attack.
Definition: attack.cpp:1535
void defend_result(hit_result res, int cth, int damage, int drain)
Definition: statistics.cpp:608
Standard logging facilities (interface).
static const map_location & null_location()
Definition: location.hpp:85
Container associating units to locations.
Definition: map.hpp:99
unsigned int num_blows
Effective number of blows, takes swarm into account.
Definition: attack.hpp:78
unsigned int max_hp
Maximum hitpoints of the unit.
Definition: attack.hpp:72
bool is_attacker
True if the unit is the attacker.
Definition: attack.hpp:52
game_events::wml_event_pump & pump()
Definition: manager.cpp:229
void set_standing(bool with_bars=true)
Sets the animation state to standing.
unsigned int max_experience
Definition: attack.hpp:67
void clear_variable(const std::string &varname)
Clears attributes config children does nothing if varname is no valid variable name.
Definition: game_data.cpp:114
unit_ability_list get_abilities(const std::string &tag_name, const map_location &loc) const
Gets the unit&#39;s active abilities of a particular type if it were on a specified location.
Definition: abilities.cpp:184
virtual bool local_checkup(const config &expected_data, config &real_data)=0
Compares data to the results calculated during the original game.
#define DBG_NG
Definition: attack.cpp:56
void unit_attack(display *disp, game_board &board, const map_location &a, const map_location &b, int damage, const attack_type &attack, const_attack_ptr secondary_attack, int swing, const std::string &hit_text, int drain_amount, const std::string &att_text, const std::vector< std::string > *extra_hit_sounds)
Make the unit on tile &#39;a&#39; attack the unit on tile &#39;b&#39;.
Definition: udisplay.cpp:596
void simulate(const combatant *prev_def)
Definition: attack.cpp:389
bool petrifies
Attack petrifies opponent when it hits.
Definition: attack.hpp:57
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:68
bool valid() const
Definition: map.hpp:276
std::shared_ptr< const attack_type > const_attack_ptr
Definition: ptr.hpp:37
static map_location::DIRECTION n
bool drains
Attack drains opponent when it hits.
Definition: attack.hpp:56
Display units performing various actions: moving, attacking, and dying.
iterator end()
Definition: unit.hpp:74
double poisoned
Resulting chance we are poisoned.
unsigned int swarm_max
Maximum number of blows with swarm (equal to num_blows if swarm isn&#39;t used).
Definition: attack.hpp:80
static game_display * get_singleton()
int combat_modifier(const unit_map &units, const gamemap &map, const map_location &loc, unit_type::ALIGNMENT alignment, bool is_fearless)
Returns the amount that a unit&#39;s damage should be multiplied by due to the current time of day...
Definition: attack.cpp:1578