The Battle for Wesnoth  1.15.2+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_specials("berserk").highest("value", 1).first;
147  if(weapon->combat_ability("berserk", 1).second) {
148  rounds = weapon->combat_ability("berserk", 1).first;
149  }
150  firststrike = weapon->bool_ability("firststrike");
151 
152  {
153  const int distance = distance_between(u_loc, opp_loc);
154  const bool out_of_range = distance > weapon->max_range() || distance < weapon->min_range();
155  disable = weapon->get_special_bool("disable") || out_of_range;
156  }
157 
158  // Handle plague.
159  unit_ability_list plague_specials = weapon->get_specials("plague");
160  plagues = !opp.get_state("unplagueable") && !plague_specials.empty() &&
161  opp.undead_variation() != "null" && !resources::gameboard->map().is_village(opp_loc);
162 
163  if(plagues) {
164  plague_type = (*plague_specials.front().first)["type"].str();
165 
166  if(plague_type.empty()) {
167  plague_type = u.type().base_id();
168  }
169  }
170 
171  // Compute chance to hit.
172  signed int cth = opp.defense_modifier(resources::gameboard->map().get_terrain(opp_loc)) + weapon->accuracy()
173  - (opp_weapon ? opp_weapon->parry() : 0);
174 
175  cth = utils::clamp(cth, 0, 100);
176 
177  unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
178  unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos);
179  cth = cth_effects.get_composite_value();
180 
181  cth = utils::clamp(cth, 0, 100);
182 
183  cth = weapon->combat_ability("chance_to_hit", cth, backstab_pos).first;
184 
185  if(opp.get_state("invulnerable")) {
186  cth = 0;
187  }
188 
189  chance_to_hit = utils::clamp(cth, 0, 100);
190 
191  // Compute base damage done with the weapon.
192  int base_damage = weapon->modified_damage(backstab_pos);
193 
194  // Get the damage multiplier applied to the base damage of the weapon.
195  int damage_multiplier = 100;
196 
197  // Time of day bonus.
198  damage_multiplier += combat_modifier(
199  resources::gameboard->units(), resources::gameboard->map(), u_loc, u.alignment(), u.is_fearless());
200 
201  // Leadership bonus.
202  int leader_bonus = under_leadership(u, u_loc, weapon, opp_weapon);
203  if(leader_bonus != 0) {
204  damage_multiplier += leader_bonus;
205  }
206 
207  // Resistance modifier.
208  damage_multiplier *= opp.damage_from(*weapon, !attacking, opp_loc, opp_weapon);
209 
210  // Compute both the normal and slowed damage.
211  damage = round_damage(base_damage, damage_multiplier, 10000);
212  slow_damage = round_damage(base_damage, damage_multiplier, 20000);
213 
214  if(is_slowed) {
216  }
217 
218  // Compute drain amounts only if draining is possible.
219  if(drains) {
220  if (weapon->get_special_bool("drains")) {
221  unit_ability_list drain_specials = weapon->get_specials("drains");
222  // Compute the drain percent (with 50% as the base for backward compatibility)
223  unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos);
224  drain_percent = drain_percent_effects.get_composite_value();
225  }
226  if (weapon->combat_ability("drains", 50, backstab_pos).second) {
227  drain_percent = weapon->combat_ability("drains", 50, backstab_pos).first;
228  }
229  }
230 
231  // Add heal_on_hit (the drain constant)
232  unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit");
233  unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos);
234  drain_constant += heal_on_hit_effects.get_composite_value();
235 
237 
238  // Compute the number of blows and handle swarm.
239  weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
242 }
243 
245  const_attack_ptr att_weapon,
246  bool attacking,
247  const unit_type* opp_type,
248  const_attack_ptr opp_weapon,
249  unsigned int opp_terrain_defense,
250  int lawful_bonus)
251  : weapon(att_weapon)
252  , attack_num(-2) // This is and stays invalid. Always use weapon when using this constructor.
253  , is_attacker(attacking)
254  , is_poisoned(false)
255  , is_slowed(false)
256  , slows(false)
257  , drains(false)
258  , petrifies(false)
259  , plagues(false)
260  , poisons(false)
261  , backstab_pos(false)
262  , swarm(false)
263  , firststrike(false)
264  , disable(false)
265  , experience(0)
266  , max_experience(0)
267  , level(0)
268  , rounds(1)
269  , hp(0)
270  , max_hp(0)
271  , chance_to_hit(0)
272  , damage(0)
273  , slow_damage(0)
274  , drain_percent(0)
275  , drain_constant(0)
276  , num_blows(0)
277  , swarm_min(0)
278  , swarm_max(0)
279  , plague_type()
280 {
281  if(!u_type || !opp_type) {
282  return;
283  }
284 
285  // Get the current state of the unit.
286  if(u_type->hitpoints() < 0) {
287  hp = 0;
288  } else {
289  hp = u_type->hitpoints();
290  }
291 
292  max_experience = u_type->experience_needed();
293  level = (u_type->level());
294  max_hp = (u_type->hitpoints());
295 
296  // Exit if no weapon.
297  if(!weapon) {
298  return;
299  }
300 
301  // Get the weapon characteristics as appropriate.
302  auto ctx = weapon->specials_context(*u_type, map_location::null_location(), attacking);
303  boost::optional<decltype(ctx)> opp_ctx;
304 
305  if(opp_weapon) {
306  opp_ctx.emplace(opp_weapon->specials_context(*opp_type, map_location::null_location(), !attacking));
307  }
308 
309  slows = weapon->get_special_bool("slow");
310  drains = !opp_type->musthave_status("undrainable") && weapon->get_special_bool("drains");
311  petrifies = weapon->get_special_bool("petrifies");
312  poisons = !opp_type->musthave_status("unpoisonable") && weapon->get_special_bool("poison");
313  rounds = weapon->get_specials("berserk").highest("value", 1).first;
314  firststrike = weapon->get_special_bool("firststrike");
315  disable = weapon->get_special_bool("disable");
316 
317  unit_ability_list plague_specials = weapon->get_specials("plague");
318  plagues = !opp_type->musthave_status("unplagueable") && !plague_specials.empty() &&
319  opp_type->undead_variation() != "null";
320 
321  if(plagues) {
322  plague_type = (*plague_specials.front().first)["type"].str();
323  if(plague_type.empty()) {
324  plague_type = u_type->base_id();
325  }
326  }
327 
328  signed int cth = 100 - opp_terrain_defense + weapon->accuracy() - (opp_weapon ? opp_weapon->parry() : 0);
329  cth = utils::clamp(cth, 0, 100);
330 
331  unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
332  unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos);
333  cth = cth_effects.get_composite_value();
334 
335  chance_to_hit = utils::clamp(cth, 0, 100);
336 
337  int base_damage = weapon->modified_damage(backstab_pos);
338  int damage_multiplier = 100;
339  damage_multiplier
340  += generic_combat_modifier(lawful_bonus, u_type->alignment(), u_type->musthave_status("fearless"), 0);
341  damage_multiplier *= opp_type->resistance_against(weapon->type(), !attacking);
342 
343  damage = round_damage(base_damage, damage_multiplier, 10000);
344  slow_damage = round_damage(base_damage, damage_multiplier, 20000);
345 
346  if(drains) {
347  unit_ability_list drain_specials = weapon->get_specials("drains");
348 
349  // Compute the drain percent (with 50% as the base for backward compatibility)
350  unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos);
351  drain_percent = drain_percent_effects.get_composite_value();
352  }
353 
354  // Add heal_on_hit (the drain constant)
355  unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit");
356  unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos);
357  drain_constant += heal_on_hit_effects.get_composite_value();
358 
360 
361  // Compute the number of blows and handle swarm.
362  weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
365 }
366 
367 
368 // ==================================================================================
369 // BATTLE CONTEXT
370 // ==================================================================================
371 
373  const unit& attacker,
374  const map_location& a_loc,
375  int a_wep_index,
376  const unit& defender,
377  const map_location& d_loc,
378  int d_wep_index,
379  const unit_map& units)
380  : attacker_stats_()
381  , defender_stats_()
382  , attacker_combatant_()
383  , defender_combatant_()
384 {
385  size_t a_wep_uindex = static_cast<size_t>(a_wep_index);
386  size_t d_wep_uindex = static_cast<size_t>(d_wep_index);
387 
388  const_attack_ptr a_wep(a_wep_uindex < attacker.attacks().size() ? attacker.attacks()[a_wep_index].shared_from_this() : nullptr);
389  const_attack_ptr d_wep(d_wep_uindex < defender.attacks().size() ? defender.attacks()[d_wep_index].shared_from_this() : nullptr);
390 
391  attacker_stats_.reset(new battle_context_unit_stats(attacker, a_loc, a_wep_index, true , defender, d_loc, d_wep, units));
392  defender_stats_.reset(new battle_context_unit_stats(defender, d_loc, d_wep_index, false, attacker, a_loc, a_wep, units));
393 }
394 
395 void battle_context::simulate(const combatant* prev_def)
396 {
397  assert((attacker_combatant_.get() != nullptr) == (defender_combatant_.get() != nullptr));
398  assert(attacker_stats_);
399  assert(defender_stats_);
400  if(!attacker_combatant_) {
402  defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
404  }
405 }
406 
407 // more like a factory method than a constructor, always calls one of the other constructors.
409  const map_location& attacker_loc,
410  const map_location& defender_loc,
411  int attacker_weapon,
412  int defender_weapon,
413  double aggression,
414  const combatant* prev_def,
415  const unit* attacker_ptr,
416  const unit* defender_ptr)
417  : attacker_stats_(nullptr)
418  , defender_stats_(nullptr)
419  , attacker_combatant_(nullptr)
420  , defender_combatant_(nullptr)
421 {
422  //TODO: maybe check before dereferencing units.find(attacker_loc),units.find(defender_loc) ?
423  const unit& attacker = attacker_ptr ? *attacker_ptr : *units.find(attacker_loc);
424  const unit& defender = defender_ptr ? *defender_ptr : *units.find(defender_loc);
425  const double harm_weight = 1.0 - aggression;
426 
427  if(attacker_weapon == -1) {
428  *this = choose_attacker_weapon(
429  attacker, defender, units, attacker_loc, defender_loc, harm_weight, prev_def
430  );
431  }
432  else if(defender_weapon == -1) {
433  *this = choose_defender_weapon(
434  attacker, defender, attacker_weapon, units, attacker_loc, defender_loc, prev_def
435  );
436  }
437  else {
438  *this = battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, defender_weapon, units);
439  }
440 
441  assert(attacker_stats_);
442  assert(defender_stats_);
443 }
444 
448  , attacker_combatant_(nullptr)
449  , defender_combatant_(nullptr)
450 {
451 }
452 
453 
454 /** @todo FIXME: better to initialize combatant initially (move into
455  battle_context_unit_stats?), just do fight() when required. */
457 {
458  // We calculate this lazily, since AI doesn't always need it.
459  simulate(prev_def);
460  return *attacker_combatant_;
461 }
462 
464 {
465  // We calculate this lazily, since AI doesn't always need it.
466  simulate(prev_def);
467  return *defender_combatant_;
468 }
469 
470 // Given this harm_weight, are we better than that other context?
471 bool battle_context::better_attack(class battle_context& that, double harm_weight)
472 {
473  return better_combat(
476  that.get_attacker_combatant(),
477  that.get_defender_combatant(),
478  harm_weight
479  );
480 }
481 
482 // Given this harm_weight, are we better than that other context?
483 bool battle_context::better_defense(class battle_context& that, double harm_weight)
484 {
485  return better_combat(
488  that.get_defender_combatant(),
489  that.get_attacker_combatant(),
490  harm_weight
491  );
492 }
493 
494 // Does combat A give us a better result than combat B?
496  const combatant& them_a,
497  const combatant& us_b,
498  const combatant& them_b,
499  double harm_weight)
500 {
501  double a, b;
502 
503  // Compare: P(we kill them) - P(they kill us).
504  a = them_a.hp_dist[0] - us_a.hp_dist[0] * harm_weight;
505  b = them_b.hp_dist[0] - us_b.hp_dist[0] * harm_weight;
506 
507  if(a - b < -0.01) {
508  return false;
509  }
510 
511  if(a - b > 0.01) {
512  return true;
513  }
514 
515  // Add poison to calculations
516  double poison_a_us = (us_a.poisoned) * game_config::poison_amount;
517  double poison_a_them = (them_a.poisoned) * game_config::poison_amount;
518  double poison_b_us = (us_b.poisoned) * game_config::poison_amount;
519  double poison_b_them = (them_b.poisoned) * game_config::poison_amount;
520 
521  // Compare: damage to them - damage to us (average_hp replaces -damage)
522  a = (us_a.average_hp() - poison_a_us) * harm_weight - (them_a.average_hp() - poison_a_them);
523  b = (us_b.average_hp() - poison_b_us) * harm_weight - (them_b.average_hp() - poison_b_them);
524 
525  if(a - b < -0.01) {
526  return false;
527  }
528 
529  if(a - b > 0.01) {
530  return true;
531  }
532 
533  // All else equal: go for most damage.
534  return them_a.average_hp() < them_b.average_hp();
535 }
536 
538  const unit& defender,
539  const unit_map& units,
540  const map_location& attacker_loc,
541  const map_location& defender_loc,
542  double harm_weight,
543  const combatant* prev_def)
544 {
545  log_scope2(log_attack, "choose_attacker_weapon");
546  std::vector<battle_context> choices;
547 
548  // What options does attacker have?
549  for(size_t i = 0; i < attacker.attacks().size(); ++i) {
550  const attack_type& att = attacker.attacks()[i];
551 
552  if(att.attack_weight() <= 0) {
553  continue;
554  }
555  battle_context bc = choose_defender_weapon(attacker, defender, i, units, attacker_loc, defender_loc, prev_def);
556  //choose_defender_weapon will always choose the weapon that disabels the attackers weapon if possible.
557  if(bc.attacker_stats_->disable) {
558  continue;
559  }
560  choices.emplace_back(std::move(bc));
561  }
562 
563  if(choices.empty()) {
564  return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
565  }
566 
567  if(choices.size() == 1) {
568  return std::move(choices[0]);
569  }
570 
571  // Multiple options: simulate them, save best.
572  battle_context* best_choice = nullptr;
573  for(auto& choice : choices) {
574  // If choose_defender_weapon didn't simulate, do so now.
575  choice.simulate(prev_def);
576 
577  if(!best_choice || choice.better_attack(*best_choice, harm_weight)) {
578  best_choice = &choice;
579  }
580  }
581 
582  if(best_choice) {
583  return std::move(*best_choice);
584  }
585  else {
586  return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
587  }
588 }
589 
590 /** @todo FIXME: Hand previous defender unit in here. */
592  const unit& defender,
593  unsigned attacker_weapon,
594  const unit_map& units,
595  const map_location& attacker_loc,
596  const map_location& defender_loc,
597  const combatant* prev_def)
598 {
599  log_scope2(log_attack, "choose_defender_weapon");
600  VALIDATE(attacker_weapon < attacker.attacks().size(), _("An invalid attacker weapon got selected."));
601 
602  const attack_type& att = attacker.attacks()[attacker_weapon];
603  auto no_weapon = [&]() { return battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, -1, units); };
604  std::vector<battle_context> choices;
605 
606  // What options does defender have?
607  for(size_t i = 0; i < defender.attacks().size(); ++i) {
608  const attack_type& def = defender.attacks()[i];
609  if(def.range() != att.range() || def.defense_weight() <= 0) {
610  //no need to calculate the battle_context here.
611  continue;
612  }
613  battle_context bc(attacker, attacker_loc, attacker_weapon, defender, defender_loc, i, units);
614 
615  if(bc.defender_stats_->disable) {
616  continue;
617  }
618  if(bc.attacker_stats_->disable) {
619  //the defenders attack disables the attakers attack: always choose this one.
620  return bc;
621  }
622  choices.emplace_back(std::move(bc));
623  }
624 
625  if(choices.empty()) {
626  return no_weapon();
627  }
628 
629  if(choices.size() == 1) {
630  //only one usable weapon, don't simulate
631  return std::move(choices[0]);
632  }
633 
634  // Multiple options:
635  // First pass : get the best weight and the minimum simple rating for this weight.
636  // simple rating = number of blows * damage per blows (resistance taken in account) * cth * weight
637  // Eligible attacks for defense should have a simple rating greater or equal to this weight.
638 
639  int min_rating = 0;
640  {
641  double max_weight = 0.0;
642 
643  for(const auto& choice : choices) {
644  const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
645 
646  if(def.defense_weight() >= max_weight) {
647  const battle_context_unit_stats& def_stats = *choice.defender_stats_;
648 
649  max_weight = def.defense_weight();
650  int rating = static_cast<int>(
651  def_stats.num_blows * def_stats.damage * def_stats.chance_to_hit * def.defense_weight());
652 
653  if(def.defense_weight() > max_weight || rating < min_rating) {
654  min_rating = rating;
655  }
656  }
657  }
658  }
659 
660  battle_context* best_choice = nullptr;
661  // Multiple options: simulate them, save best.
662  for(auto& choice : choices) {
663  const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
664 
665  choice.simulate(prev_def);
666 
667 
668  int simple_rating = static_cast<int>(
669  choice.defender_stats_->num_blows * choice.defender_stats_->damage * choice.defender_stats_->chance_to_hit * def.defense_weight());
670 
671  //FIXME: make sure there is no mostake in the better_combat call-
672  if(simple_rating >= min_rating && (!best_choice || choice.better_defense(*best_choice, 1.0))) {
673  best_choice = &choice;
674  }
675  }
676 
677  return best_choice ? std::move(*best_choice) : no_weapon();
678 }
679 
680 
681 // ==================================================================================
682 // HELPERS
683 // ==================================================================================
684 
685 namespace
686 {
687 void refresh_weapon_index(int& weap_index, const std::string& weap_id, attack_itors attacks)
688 {
689  // No attacks to choose from.
690  if(attacks.empty()) {
691  weap_index = -1;
692  return;
693  }
694 
695  // The currently selected attack fits.
696  if(weap_index >= 0 && weap_index < static_cast<int>(attacks.size()) && attacks[weap_index].id() == weap_id) {
697  return;
698  }
699 
700  // Look up the weapon by id.
701  if(!weap_id.empty()) {
702  for(int i = 0; i < static_cast<int>(attacks.size()); ++i) {
703  if(attacks[i].id() == weap_id) {
704  weap_index = i;
705  return;
706  }
707  }
708  }
709 
710  // Lookup has failed.
711  weap_index = -1;
712  return;
713 }
714 
715 /** Helper class for performing an attack. */
716 class attack
717 {
718 public:
719  attack(const map_location& attacker,
720  const map_location& defender,
721  int attack_with,
722  int defend_with,
723  bool update_display = true);
724 
725  void perform();
726 
727 private:
728  class attack_end_exception
729  {
730  };
731 
732  bool perform_hit(bool, statistics::attack_context&);
733  void fire_event(const std::string& n);
734  void refresh_bc();
735 
736  /** Structure holding unit info used in the attack action. */
737  struct unit_info
738  {
739  const map_location loc_;
740  int weapon_;
741  unit_map& units_;
742  std::size_t id_; /**< unit.underlying_id() */
743  std::string weap_id_;
744  int orig_attacks_;
745  int n_attacks_; /**< Number of attacks left. */
746  int cth_;
747  int damage_;
748  int xp_;
749 
750  unit_info(const map_location& loc, int weapon, unit_map& units);
751  unit& get_unit();
752  bool valid();
753 
754  std::string dump();
755  };
756 
757  /**
758  * Used in perform_hit to confirm a replay is in sync.
759  * Check OOS_error_ after this method, true if error detected.
760  */
761  void check_replay_attack_result(bool&, int, int&, config, unit_info&);
762 
763  void unit_killed(
764  unit_info&, unit_info&, const battle_context_unit_stats*&, const battle_context_unit_stats*&, bool);
765 
766  std::unique_ptr<battle_context> bc_;
767 
768  const battle_context_unit_stats* a_stats_;
769  const battle_context_unit_stats* d_stats_;
770 
771  int abs_n_attack_, abs_n_defend_;
772  // update_att_fog_ is not used, other than making some code simpler.
773  bool update_att_fog_, update_def_fog_, update_minimap_;
774 
775  unit_info a_, d_;
776  unit_map& units_;
777  std::ostringstream errbuf_;
778 
779  bool update_display_;
780  bool OOS_error_;
781 
782  bool use_prng_;
783 
784  std::vector<bool> prng_attacker_;
785  std::vector<bool> prng_defender_;
786 };
787 
788 attack::unit_info::unit_info(const map_location& loc, int weapon, unit_map& units)
789  : loc_(loc)
790  , weapon_(weapon)
791  , units_(units)
792  , id_()
793  , weap_id_()
794  , orig_attacks_(0)
795  , n_attacks_(0)
796  , cth_(0)
797  , damage_(0)
798  , xp_(0)
799 {
800  unit_map::iterator i = units_.find(loc_);
801  if(!i.valid()) {
802  return;
803  }
804 
805  id_ = i->underlying_id();
806 }
807 
808 unit& attack::unit_info::get_unit()
809 {
810  unit_map::iterator i = units_.find(loc_);
811  assert(i.valid() && i->underlying_id() == id_);
812  return *i;
813 }
814 
815 bool attack::unit_info::valid()
816 {
817  unit_map::iterator i = units_.find(loc_);
818  return i.valid() && i->underlying_id() == id_;
819 }
820 
821 std::string attack::unit_info::dump()
822 {
823  std::stringstream s;
824  s << get_unit().type_id() << " (" << loc_.wml_x() << ',' << loc_.wml_y() << ')';
825  return s.str();
826 }
827 
828 attack::attack(const map_location& attacker,
829  const map_location& defender,
830  int attack_with,
831  int defend_with,
832  bool update_display)
833  : bc_(nullptr)
834  , a_stats_(nullptr)
835  , d_stats_(nullptr)
836  , abs_n_attack_(0)
837  , abs_n_defend_(0)
838  , update_att_fog_(false)
839  , update_def_fog_(false)
840  , update_minimap_(false)
841  , a_(attacker, attack_with, resources::gameboard->units())
842  , d_(defender, defend_with, resources::gameboard->units())
843  , units_(resources::gameboard->units())
844  , errbuf_()
845  , update_display_(update_display)
846  , OOS_error_(false)
847 
848  //new experimental prng mode.
849  , use_prng_(preferences::get("use_prng") == "yes" && randomness::generator->is_networked() == false)
850 {
851  if(use_prng_) {
852  std::cerr << "Using experimental PRNG for combat\n";
853  }
854 }
855 
856 void attack::fire_event(const std::string& n)
857 {
858  LOG_NG << "attack: firing '" << n << "' event\n";
859 
860  // prepare the event data for weapon filtering
861  config ev_data;
862  config& a_weapon_cfg = ev_data.add_child("first");
863  config& d_weapon_cfg = ev_data.add_child("second");
864 
865  // Need these to ensure weapon filters work correctly
866  boost::optional<attack_type::specials_context_t> a_ctx, d_ctx;
867 
868  if(a_stats_->weapon != nullptr && a_.valid()) {
869  if(d_stats_->weapon != nullptr && d_.valid()) {
870  a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, nullptr, a_.loc_, d_.loc_, true, d_stats_->weapon));
871  } else {
872  a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, a_.loc_, true));
873  }
874  a_stats_->weapon->write(a_weapon_cfg);
875  }
876 
877  if(d_stats_->weapon != nullptr && d_.valid()) {
878  if(a_stats_->weapon != nullptr && a_.valid()) {
879  d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, nullptr, d_.loc_, a_.loc_, false, a_stats_->weapon));
880  } else {
881  d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, d_.loc_, false));
882  }
883  d_stats_->weapon->write(d_weapon_cfg);
884  }
885 
886  if(a_weapon_cfg["name"].empty()) {
887  a_weapon_cfg["name"] = "none";
888  }
889 
890  if(d_weapon_cfg["name"].empty()) {
891  d_weapon_cfg["name"] = "none";
892  }
893 
894  if(n == "attack_end") {
895  // We want to fire attack_end event in any case! Even if one of units was removed by WML.
896  resources::game_events->pump().fire(n, a_.loc_, d_.loc_, ev_data);
897  return;
898  }
899 
900  // damage_inflicted is set in these two events.
901  // TODO: should we set this value from unit_info::damage, or continue using the WML variable?
902  if(n == "attacker_hits" || n == "defender_hits") {
903  ev_data["damage_inflicted"] = resources::gamedata->get_variable("damage_inflicted");
904  }
905 
906  const int defender_side = d_.get_unit().side();
907 
908  bool wml_aborted;
909  std::tie(std::ignore, wml_aborted) = resources::game_events->pump().fire(n,
911  game_events::entity_location(d_.loc_, d_.id_), ev_data);
912 
913  // The event could have killed either the attacker or
914  // defender, so we have to make sure they still exist.
915  refresh_bc();
916 
917  if(wml_aborted || !a_.valid() || !d_.valid()
918  || !resources::gameboard->get_team(a_.get_unit().side()).is_enemy(d_.get_unit().side())
919  ) {
920  actions::recalculate_fog(defender_side);
921 
922  if(update_display_) {
924  }
925 
926  fire_event("attack_end");
927  throw attack_end_exception();
928  }
929 }
930 
931 void attack::refresh_bc()
932 {
933  // Fix index of weapons.
934  if(a_.valid()) {
935  refresh_weapon_index(a_.weapon_, a_.weap_id_, a_.get_unit().attacks());
936  }
937 
938  if(d_.valid()) {
939  refresh_weapon_index(d_.weapon_, d_.weap_id_, d_.get_unit().attacks());
940  }
941 
942  if(!a_.valid() || !d_.valid()) {
943  // Fix pointer to weapons.
944  const_cast<battle_context_unit_stats*>(a_stats_)->weapon
945  = a_.valid() && a_.weapon_ >= 0 ? a_.get_unit().attacks()[a_.weapon_].shared_from_this() : nullptr;
946 
947  const_cast<battle_context_unit_stats*>(d_stats_)->weapon
948  = d_.valid() && d_.weapon_ >= 0 ? d_.get_unit().attacks()[d_.weapon_].shared_from_this() : nullptr;
949 
950  return;
951  }
952 
953  bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_));
954 
955  a_stats_ = &bc_->get_attacker_stats();
956  d_stats_ = &bc_->get_defender_stats();
957 
958  a_.cth_ = a_stats_->chance_to_hit;
959  d_.cth_ = d_stats_->chance_to_hit;
960  a_.damage_ = a_stats_->damage;
961  d_.damage_ = d_stats_->damage;
962 }
963 
964 bool attack::perform_hit(bool attacker_turn, statistics::attack_context& stats)
965 {
966  unit_info& attacker = attacker_turn ? a_ : d_;
967  unit_info& defender = attacker_turn ? d_ : a_;
968 
969  // NOTE: we need to use a reference-to-pointer here so a_stats_ and d_stats_ can be
970  // modified without. Using a pointer directly would render them invalid when that happened.
971  const battle_context_unit_stats*& attacker_stats = attacker_turn ? a_stats_ : d_stats_;
972  const battle_context_unit_stats*& defender_stats = attacker_turn ? d_stats_ : a_stats_;
973 
974  int& abs_n = attacker_turn ? abs_n_attack_ : abs_n_defend_;
975  bool& update_fog = attacker_turn ? update_def_fog_ : update_att_fog_;
976 
977  int ran_num;
978 
979  if(use_prng_) {
980 
981  std::vector<bool>& prng_seq = attacker_turn ? prng_attacker_ : prng_defender_;
982 
983  if(prng_seq.empty()) {
984  const int ntotal = attacker.cth_*attacker.n_attacks_;
985  int num_hits = ntotal/100;
986  const int additional_hit_chance = ntotal%100;
987  if(additional_hit_chance > 0 && randomness::generator->get_random_int(0, 99) < additional_hit_chance) {
988  ++num_hits;
989  }
990 
991  std::vector<int> indexes;
992  for(int i = 0; i != attacker.n_attacks_; ++i) {
993  prng_seq.push_back(false);
994  indexes.push_back(i);
995  }
996 
997  for(int i = 0; i != num_hits; ++i) {
998  int n = randomness::generator->get_random_int(0, static_cast<int>(indexes.size())-1);
999  prng_seq[indexes[n]] = true;
1000  indexes.erase(indexes.begin() + n);
1001  }
1002  }
1003 
1004  bool does_hit = prng_seq.back();
1005  prng_seq.pop_back();
1006  ran_num = does_hit ? 0 : 99;
1007  } else {
1008  ran_num = randomness::generator->get_random_int(0, 99);
1009  }
1010  bool hits = (ran_num < attacker.cth_);
1011 
1012  int damage = 0;
1013  if(hits) {
1014  damage = attacker.damage_;
1015  resources::gamedata->get_variable("damage_inflicted") = damage;
1016  }
1017 
1018  // Make sure that if we're serializing a game here,
1019  // we got the same results as the game did originally.
1020  const config local_results {"chance", attacker.cth_, "hits", hits, "damage", damage};
1021 
1022  config replay_results;
1023  bool equals_replay = checkup_instance->local_checkup(local_results, replay_results);
1024 
1025  if(!equals_replay) {
1026  check_replay_attack_result(hits, ran_num, damage, replay_results, attacker);
1027  }
1028 
1029  // can do no more damage than the defender has hitpoints
1030  int damage_done = std::min<int>(defender.get_unit().hitpoints(), attacker.damage_);
1031 
1032  // expected damage = damage potential * chance to hit (as a percentage)
1033  double expected_damage = damage_done * attacker.cth_ * 0.01;
1034 
1035  if(attacker_turn) {
1036  stats.attack_expected_damage(expected_damage, 0);
1037  } else {
1038  stats.attack_expected_damage(0, expected_damage);
1039  }
1040 
1041  int drains_damage = 0;
1042  if(hits && attacker_stats->drains) {
1043  drains_damage = damage_done * attacker_stats->drain_percent / 100 + attacker_stats->drain_constant;
1044 
1045  // don't drain so much that the attacker gets more than his maximum hitpoints
1046  drains_damage =
1047  std::min<int>(drains_damage, attacker.get_unit().max_hitpoints() - attacker.get_unit().hitpoints());
1048 
1049  // if drain is negative, don't allow drain to kill the attacker
1050  drains_damage = std::max<int>(drains_damage, 1 - attacker.get_unit().hitpoints());
1051  }
1052 
1053  if(update_display_) {
1054  std::ostringstream float_text;
1055  std::vector<std::string> extra_hit_sounds;
1056 
1057  if(hits) {
1058  const unit& defender_unit = defender.get_unit();
1059  if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
1060  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^poisoned") : _("poisoned"))
1061  << '\n';
1062 
1063  extra_hit_sounds.push_back(game_config::sounds::status::poisoned);
1064  }
1065 
1066  if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
1067  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^slowed") : _("slowed")) << '\n';
1068 
1069  extra_hit_sounds.push_back(game_config::sounds::status::slowed);
1070  }
1071 
1072  if(attacker_stats->petrifies) {
1073  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^petrified") : _("petrified"))
1074  << '\n';
1075 
1076  extra_hit_sounds.push_back(game_config::sounds::status::petrified);
1077  }
1078  }
1079 
1083  attacker.loc_, defender.loc_,
1084  damage,
1085  *attacker_stats->weapon, defender_stats->weapon,
1086  abs_n, float_text.str(), drains_damage, "",
1087  &extra_hit_sounds
1088  );
1089  }
1090 
1091  bool dies = defender.get_unit().take_hit(damage);
1092  LOG_NG << "defender took " << damage << (dies ? " and died\n" : "\n");
1093 
1094  if(attacker_turn) {
1095  stats.attack_result(hits
1096  ? (dies
1100  attacker.cth_, damage_done, drains_damage
1101  );
1102  } else {
1103  stats.defend_result(hits
1104  ? (dies
1108  attacker.cth_, damage_done, drains_damage
1109  );
1110  }
1111 
1112  replay_results.clear();
1113 
1114  // There was also a attribute cfg["unit_hit"] which was never used so i deleted.
1115  equals_replay = checkup_instance->local_checkup(config{"dies", dies}, replay_results);
1116 
1117  if(!equals_replay) {
1118  bool results_dies = replay_results["dies"].to_bool();
1119 
1120  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the "
1121  << (attacker_turn ? "defender" : "attacker") << ' ' << (results_dies ? "perished" : "survived")
1122  << " while in-game calculations show it " << (dies ? "perished" : "survived")
1123  << " (over-riding game calculations with data source results)\n";
1124 
1125  dies = results_dies;
1126 
1127  // Set hitpoints to 0 so later checks don't invalidate the death.
1128  if(results_dies) {
1129  defender.get_unit().set_hitpoints(0);
1130  }
1131 
1132  OOS_error_ = true;
1133  }
1134 
1135  if(hits) {
1136  try {
1137  fire_event(attacker_turn ? "attacker_hits" : "defender_hits");
1138  } catch(const attack_end_exception&) {
1139  refresh_bc();
1140  return false;
1141  }
1142  } else {
1143  try {
1144  fire_event(attacker_turn ? "attacker_misses" : "defender_misses");
1145  } catch(const attack_end_exception&) {
1146  refresh_bc();
1147  return false;
1148  }
1149  }
1150 
1151  refresh_bc();
1152 
1153  bool attacker_dies = false;
1154 
1155  if(drains_damage > 0) {
1156  attacker.get_unit().heal(drains_damage);
1157  } else if(drains_damage < 0) {
1158  attacker_dies = attacker.get_unit().take_hit(-drains_damage);
1159  }
1160 
1161  if(dies) {
1162  unit_killed(attacker, defender, attacker_stats, defender_stats, false);
1163  update_fog = true;
1164  }
1165 
1166  if(attacker_dies) {
1167  unit_killed(defender, attacker, defender_stats, attacker_stats, true);
1168  (attacker_turn ? update_att_fog_ : update_def_fog_) = true;
1169  }
1170 
1171  if(dies) {
1172  update_minimap_ = true;
1173  return false;
1174  }
1175 
1176  if(hits) {
1177  unit& defender_unit = defender.get_unit();
1178 
1179  if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
1180  defender_unit.set_state(unit::STATE_POISONED, true);
1181  LOG_NG << "defender poisoned\n";
1182  }
1183 
1184  if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
1185  defender_unit.set_state(unit::STATE_SLOWED, true);
1186  update_fog = true;
1187  defender.damage_ = defender_stats->slow_damage;
1188  LOG_NG << "defender slowed\n";
1189  }
1190 
1191  // If the defender is petrified, the fight stops immediately
1192  if(attacker_stats->petrifies) {
1193  defender_unit.set_state(unit::STATE_PETRIFIED, true);
1194  update_fog = true;
1195  attacker.n_attacks_ = 0;
1196  defender.n_attacks_ = -1; // Petrified.
1197  resources::game_events->pump().fire("petrified", defender.loc_, attacker.loc_);
1198  refresh_bc();
1199  }
1200  }
1201 
1202  // Delay until here so that poison and slow go through
1203  if(attacker_dies) {
1204  update_minimap_ = true;
1205  return false;
1206  }
1207 
1208  --attacker.n_attacks_;
1209  return true;
1210 }
1211 
1212 void attack::unit_killed(unit_info& attacker,
1213  unit_info& defender,
1214  const battle_context_unit_stats*& attacker_stats,
1215  const battle_context_unit_stats*& defender_stats,
1216  bool drain_killed)
1217 {
1218  attacker.xp_ = game_config::kill_xp(defender.get_unit().level());
1219  defender.xp_ = 0;
1220 
1221  display::get_singleton()->invalidate(attacker.loc_);
1222 
1223  game_events::entity_location death_loc(defender.loc_, defender.id_);
1224  game_events::entity_location attacker_loc(attacker.loc_, attacker.id_);
1225 
1226  std::string undead_variation = defender.get_unit().undead_variation();
1227 
1228  fire_event("attack_end");
1229  refresh_bc();
1230 
1231  // Get weapon info for last_breath and die events.
1232  config dat;
1233  config a_weapon_cfg = attacker_stats->weapon && attacker.valid() ? attacker_stats->weapon->to_config() : config();
1234  config d_weapon_cfg = defender_stats->weapon && defender.valid() ? defender_stats->weapon->to_config() : config();
1235 
1236  if(a_weapon_cfg["name"].empty()) {
1237  a_weapon_cfg["name"] = "none";
1238  }
1239 
1240  if(d_weapon_cfg["name"].empty()) {
1241  d_weapon_cfg["name"] = "none";
1242  }
1243 
1244  dat.add_child("first", d_weapon_cfg);
1245  dat.add_child("second", a_weapon_cfg);
1246 
1247  resources::game_events->pump().fire("last_breath", death_loc, attacker_loc, dat);
1248  refresh_bc();
1249 
1250  // WML has invalidated the dying unit, abort.
1251  if(!defender.valid() || defender.get_unit().hitpoints() > 0) {
1252  return;
1253  }
1254 
1255  if(!attacker.valid()) {
1257  defender.loc_,
1258  defender.get_unit(),
1259  nullptr,
1260  defender_stats->weapon
1261  );
1262  } else {
1264  defender.loc_,
1265  defender.get_unit(),
1266  attacker_stats->weapon,
1267  defender_stats->weapon,
1268  attacker.loc_,
1269  &attacker.get_unit()
1270  );
1271  }
1272 
1273  resources::game_events->pump().fire("die", death_loc, attacker_loc, dat);
1274  refresh_bc();
1275 
1276  if(!defender.valid() || defender.get_unit().hitpoints() > 0) {
1277  // WML has invalidated the dying unit, abort
1278  return;
1279  }
1280 
1281  units_.erase(defender.loc_);
1282  resources::whiteboard->on_kill_unit();
1283 
1284  // Plague units make new units on the target hex.
1285  if(attacker.valid() && attacker_stats->plagues && !drain_killed) {
1286  LOG_NG << "trying to reanimate " << attacker_stats->plague_type << '\n';
1287 
1288  if(const unit_type* reanimator = unit_types.find(attacker_stats->plague_type)) {
1289  LOG_NG << "found unit type:" << reanimator->id() << '\n';
1290 
1291  unit_ptr newunit = unit::create(*reanimator, attacker.get_unit().side(), true, unit_race::MALE);
1292  newunit->set_attacks(0);
1293  newunit->set_movement(0, true);
1294  newunit->set_facing(map_location::get_opposite_dir(attacker.get_unit().facing()));
1295 
1296  // Apply variation
1297  if(undead_variation != "null") {
1298  config mod;
1299  config& variation = mod.add_child("effect");
1300  variation["apply_to"] = "variation";
1301  variation["name"] = undead_variation;
1302  newunit->add_modification("variation", mod);
1303  newunit->heal_fully();
1304  }
1305 
1306  newunit->set_location(death_loc);
1307  units_.insert(newunit);
1308 
1309  game_events::entity_location reanim_loc(defender.loc_, newunit->underlying_id());
1310  resources::game_events->pump().fire("unit_placed", reanim_loc);
1311 
1312  preferences::encountered_units().insert(newunit->type_id());
1313 
1314  if(update_display_) {
1315  display::get_singleton()->invalidate(death_loc);
1316  }
1317  }
1318  } else {
1319  LOG_NG << "unit not reanimated\n";
1320  }
1321 }
1322 
1323 void attack::perform()
1324 {
1325  // Stop the user from issuing any commands while the units are fighting.
1326  const events::command_disabler disable_commands;
1327 
1328  if(!a_.valid() || !d_.valid()) {
1329  return;
1330  }
1331 
1332  // no attack weapon => stop here and don't attack
1333  if(a_.weapon_ < 0) {
1334  a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1);
1335  a_.get_unit().set_movement(-1, true);
1336  return;
1337  }
1338 
1339  if(a_.get_unit().attacks_left() <= 0) {
1340  LOG_NG << "attack::perform(): not enough ap.\n";
1341  return;
1342  }
1343 
1344  a_.get_unit().set_facing(a_.loc_.get_relative_dir(d_.loc_));
1345  d_.get_unit().set_facing(d_.loc_.get_relative_dir(a_.loc_));
1346 
1347  a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1);
1348 
1349  VALIDATE(a_.weapon_ < static_cast<int>(a_.get_unit().attacks().size()),
1350  _("An invalid attacker weapon got selected."));
1351 
1352  a_.get_unit().set_movement(a_.get_unit().movement_left() - a_.get_unit().attacks()[a_.weapon_].movement_used(), true);
1353  a_.get_unit().set_state(unit::STATE_NOT_MOVED, false);
1354  a_.get_unit().set_resting(false);
1355  d_.get_unit().set_resting(false);
1356 
1357  // If the attacker was invisible, she isn't anymore!
1358  a_.get_unit().set_state(unit::STATE_UNCOVERED, true);
1359 
1360  bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_));
1361 
1362  a_stats_ = &bc_->get_attacker_stats();
1363  d_stats_ = &bc_->get_defender_stats();
1364 
1365  if(a_stats_->disable) {
1366  LOG_NG << "attack::perform(): tried to attack with a disabled attack.\n";
1367  return;
1368  }
1369 
1370  if(a_stats_->weapon) {
1371  a_.weap_id_ = a_stats_->weapon->id();
1372  }
1373 
1374  if(d_stats_->weapon) {
1375  d_.weap_id_ = d_stats_->weapon->id();
1376  }
1377 
1378  try {
1379  fire_event("attack");
1380  } catch(const attack_end_exception&) {
1381  return;
1382  }
1383 
1384  refresh_bc();
1385 
1386  DBG_NG << "getting attack statistics\n";
1387  statistics::attack_context attack_stats(
1388  a_.get_unit(), d_.get_unit(), a_stats_->chance_to_hit, d_stats_->chance_to_hit);
1389 
1390  a_.orig_attacks_ = a_stats_->num_blows;
1391  d_.orig_attacks_ = d_stats_->num_blows;
1392  a_.n_attacks_ = a_.orig_attacks_;
1393  d_.n_attacks_ = d_.orig_attacks_;
1394  a_.xp_ = game_config::combat_xp(d_.get_unit().level());
1395  d_.xp_ = game_config::combat_xp(a_.get_unit().level());
1396 
1397  bool defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
1398  unsigned int rounds = std::max<unsigned int>(a_stats_->rounds, d_stats_->rounds) - 1;
1399  const int defender_side = d_.get_unit().side();
1400 
1401  LOG_NG << "Fight: (" << a_.loc_ << ") vs (" << d_.loc_ << ") ATT: " << a_stats_->weapon->name() << " "
1402  << a_stats_->damage << "-" << a_stats_->num_blows << "(" << a_stats_->chance_to_hit
1403  << "%) vs DEF: " << (d_stats_->weapon ? d_stats_->weapon->name() : "none") << " " << d_stats_->damage << "-"
1404  << d_stats_->num_blows << "(" << d_stats_->chance_to_hit << "%)"
1405  << (defender_strikes_first ? " defender first-strike" : "") << "\n";
1406 
1407  // Play the pre-fight animation
1408  unit_display::unit_draw_weapon(a_.loc_, a_.get_unit(), a_stats_->weapon, d_stats_->weapon, d_.loc_, &d_.get_unit());
1409 
1410  for(;;) {
1411  DBG_NG << "start of attack loop...\n";
1412  ++abs_n_attack_;
1413 
1414  if(a_.n_attacks_ > 0 && !defender_strikes_first) {
1415  if(!perform_hit(true, attack_stats)) {
1416  DBG_NG << "broke from attack loop on attacker turn\n";
1417  break;
1418  }
1419  }
1420 
1421  // If the defender got to strike first, they use it up here.
1422  defender_strikes_first = false;
1423  ++abs_n_defend_;
1424 
1425  if(d_.n_attacks_ > 0) {
1426  if(!perform_hit(false, attack_stats)) {
1427  DBG_NG << "broke from attack loop on defender turn\n";
1428  break;
1429  }
1430  }
1431 
1432  // Continue the fight to death; if one of the units got petrified,
1433  // either n_attacks or n_defends is -1
1434  if(rounds > 0 && d_.n_attacks_ == 0 && a_.n_attacks_ == 0) {
1435  a_.n_attacks_ = a_.orig_attacks_;
1436  d_.n_attacks_ = d_.orig_attacks_;
1437  --rounds;
1438  defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
1439  }
1440 
1441  if(a_.n_attacks_ <= 0 && d_.n_attacks_ <= 0) {
1442  fire_event("attack_end");
1443  refresh_bc();
1444  break;
1445  }
1446  }
1447 
1448  // Set by attacker_hits and defender_hits events.
1449  resources::gamedata->clear_variable("damage_inflicted");
1450 
1451  if(update_def_fog_) {
1452  actions::recalculate_fog(defender_side);
1453  }
1454 
1455  // TODO: if we knew the viewing team, we could skip this display update
1456  if(update_minimap_ && update_display_) {
1458  }
1459 
1460  if(a_.valid()) {
1461  unit& u = a_.get_unit();
1462  u.anim_comp().set_standing();
1463  u.set_experience(u.experience() + a_.xp_);
1464  }
1465 
1466  if(d_.valid()) {
1467  unit& u = d_.get_unit();
1468  u.anim_comp().set_standing();
1469  u.set_experience(u.experience() + d_.xp_);
1470  }
1471 
1472  unit_display::unit_sheath_weapon(a_.loc_, a_.valid() ? &a_.get_unit() : nullptr, a_stats_->weapon, d_stats_->weapon,
1473  d_.loc_, d_.valid() ? &d_.get_unit() : nullptr);
1474 
1475  if(update_display_) {
1478  display::get_singleton()->invalidate(d_.loc_);
1479  }
1480 
1481  if(OOS_error_) {
1482  replay::process_error(errbuf_.str());
1483  }
1484 }
1485 
1486 void attack::check_replay_attack_result(
1487  bool& hits, int ran_num, int& damage, config replay_results, unit_info& attacker)
1488 {
1489  int results_chance = replay_results["chance"];
1490  bool results_hits = replay_results["hits"].to_bool();
1491  int results_damage = replay_results["damage"];
1492 
1493 #if 0
1494  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
1495  << " replay data differs from local calculated data:"
1496  << " chance to hit in data source: " << results_chance
1497  << " chance to hit in calculated: " << attacker.cth_
1498  << " chance to hit in data source: " << results_chance
1499  << " chance to hit in calculated: " << attacker.cth_
1500  ;
1501 
1502  attacker.cth_ = results_chance;
1503  hits = results_hits;
1504  damage = results_damage;
1505 
1506  OOS_error_ = true;
1507 #endif
1508 
1509  if(results_chance != attacker.cth_) {
1510  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
1511  << ": chance to hit is inconsistent. Data source: " << results_chance
1512  << "; Calculation: " << attacker.cth_ << " (over-riding game calculations with data source results)\n";
1513  attacker.cth_ = results_chance;
1514  OOS_error_ = true;
1515  }
1516 
1517  if(results_hits != hits) {
1518  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit was "
1519  << (results_hits ? "successful" : "unsuccessful") << ", while in-game calculations say the hit was "
1520  << (hits ? "successful" : "unsuccessful") << " random number: " << ran_num << " = " << (ran_num % 100)
1521  << "/" << results_chance << " (over-riding game calculations with data source results)\n";
1522  hits = results_hits;
1523  OOS_error_ = true;
1524  }
1525 
1526  if(results_damage != damage) {
1527  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit did "
1528  << results_damage << " damage, while in-game calculations show the hit doing " << damage
1529  << " damage (over-riding game calculations with data source results)\n";
1530  damage = results_damage;
1531  OOS_error_ = true;
1532  }
1533 }
1534 } // end anonymous namespace
1535 
1536 
1537 // ==================================================================================
1538 // FREE-STANDING FUNCTIONS
1539 // ==================================================================================
1540 
1541 void attack_unit(const map_location& attacker,
1542  const map_location& defender,
1543  int attack_with,
1544  int defend_with,
1545  bool update_display)
1546 {
1547  attack dummy(attacker, defender, attack_with, defend_with, update_display);
1548  dummy.perform();
1549 }
1550 
1552  const map_location& defender,
1553  int attack_with,
1554  int defend_with,
1555  bool update_display)
1556 {
1557  attack_unit(attacker, defender, attack_with, defend_with, update_display);
1558 
1560  if(atku != resources::gameboard->units().end()) {
1562  }
1563 
1565  if(defu != resources::gameboard->units().end()) {
1567  }
1568 }
1569 
1570 int under_leadership(const unit &u, const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon)
1571 {
1572  unit_ability_list abil = u.get_abilities("leadership", loc, weapon, opp_weapon);
1573  unit_abilities::effect leader_effect(abil, 0, false);
1574  return leader_effect.get_composite_value();
1575 }
1576 
1577 //begin of weapon emulates function.
1578 
1579 bool unit::abilities_filter_matches(const config& cfg, bool attacker, int res) const
1580 {
1581  if(!(cfg["active_on"].empty() || (attacker && cfg["active_on"] == "offense") || (!attacker && cfg["active_on"] == "defense"))) {
1582  return false;
1583  }
1584 
1585  if(!unit_abilities::filter_base_matches(cfg, res)) {
1586  return false;
1587  }
1588 
1589  return true;
1590 }
1591 
1592 //functions for emulate weapon specials.
1593 //filter opponent and affect self/opponent/both option.
1594 bool unit::ability_filter_fighter(const std::string& ability, const std::string& filter_attacker , const config& cfg, const map_location& loc, const unit& u2) const
1595 {
1596  const config &filter = cfg.child(filter_attacker);
1597  if(!filter) {
1598  return true;
1599  }
1600  return unit_filter(vconfig(filter)).set_use_flat_tod(ability == "illuminates").matches(*this, loc, u2);
1601 }
1602 
1603 static bool ability_apply_filter(const unit_map::const_iterator un, const unit_map::const_iterator up, const std::string& ability, const config& cfg, const map_location& loc, const map_location& opp_loc, bool attacker )
1604 {
1605  if(!up->ability_filter_fighter(ability, "filter_opponent", cfg, opp_loc, *un)){
1606  return true;
1607  }
1608  if(!un->ability_filter_fighter(ability, "filter_student", cfg, loc, *up)){
1609  return true;
1610  }
1611  if((attacker && !un->ability_filter_fighter(ability, "filter_attacker", cfg, loc, *up)) || (!attacker && !up->ability_filter_fighter(ability, "filter_attacker", cfg, opp_loc, *un))){
1612  return true;
1613  }
1614  if((!attacker && !un->ability_filter_fighter(ability, "filter_defender", cfg, loc, *up)) || (attacker && !up->ability_filter_fighter(ability, "filter_defender", cfg, opp_loc, *un))){
1615  return true;
1616  }
1617  return false;
1618 }
1619 
1620 bool leadership_affects_self(const std::string& ability,const unit_map& units, const map_location& loc, bool attacker, const_attack_ptr weapon,const_attack_ptr opp_weapon)
1621 {
1622  const unit_map::const_iterator un = units.find(loc);
1623  if(un == units.end()) {
1624  return false;
1625  }
1626 
1627  unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon);
1628  for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
1629  const std::string& apply_to = (*i->first)["apply_to"];
1630  if(apply_to.empty() || apply_to == "both" || apply_to == "self") {
1631  return true;
1632  }
1633  if(attacker && apply_to == "attacker") {
1634  return true;
1635  }
1636  if(!attacker && apply_to == "defender") {
1637  return true;
1638  }
1639  ++i;
1640  }
1641  return false;
1642 }
1643 
1644 bool leadership_affects_opponent(const std::string& ability,const unit_map& units, const map_location& loc, bool attacker, const_attack_ptr weapon,const_attack_ptr opp_weapon)
1645 {
1646  const unit_map::const_iterator un = units.find(loc);
1647  if(un == units.end()) {
1648  return false;
1649  }
1650 
1651  unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon);
1652  for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
1653  const std::string& apply_to = (*i->first)["apply_to"];
1654  if(apply_to == "both" || apply_to == "opponent") {
1655  return true;
1656  }
1657  if(attacker && apply_to == "defender") {
1658  return true;
1659  }
1660  if(!attacker && apply_to == "attacker") {
1661  return true;
1662  }
1663  ++i;
1664  }
1665  return false;
1666 }
1667 
1668 //sub function for emulate chance_to_hit,damage drains and attacks special.
1669 std::pair<int, bool> ability_leadership(const std::string& ability,const unit_map& units, const map_location& loc, const map_location& opp_loc, bool attacker, int abil_value, bool backstab_pos, const_attack_ptr weapon, const_attack_ptr opp_weapon)
1670 {
1671  const unit_map::const_iterator un = units.find(loc);
1672  const unit_map::const_iterator up = units.find(opp_loc);
1673  if(un == units.end()) {
1674  return {abil_value, false};
1675  }
1676 
1677  unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon);
1678  for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
1679  const config &filter = (*i->first).child("filter_opponent");
1680  const config &filter_student = (*i->first).child("filter_student");
1681  const config &filter_attacker = (*i->first).child("filter_attacker");
1682  const config &filter_defender = (*i->first).child("filter_defender");
1683  bool show_result = false;
1684  if(up == units.end() && !filter_student && !filter && !filter_attacker && !filter_defender) {
1685  show_result = un->abilities_filter_matches(*i->first, attacker, abil_value);
1686  } else if(up == units.end() && (filter_student || filter || filter_attacker || filter_defender)) {
1687  return {abil_value, false};
1688  } else {
1689  show_result = !(!un->abilities_filter_matches(*i->first, attacker, abil_value) || ability_apply_filter(un, up, ability, *i->first, loc, opp_loc, attacker));
1690  }
1691 
1692  if(!show_result) {
1693  i = abil.erase(i);
1694  } else {
1695  ++i;
1696  }
1697  }
1698 
1699  if(!abil.empty()) {
1700  unit_abilities::effect leader_effect(abil, abil_value, backstab_pos);
1701  return {leader_effect.get_composite_value(), true};
1702  }
1703  return {abil_value, false};
1704 }
1705 
1706 //sub function for wmulate boolean special(slow, poison...)
1707 bool bool_leadership(const std::string& ability,const unit_map& units, const map_location& loc, const map_location& opp_loc, bool attacker, const_attack_ptr weapon, const_attack_ptr opp_weapon)
1708 {
1709  const unit_map::const_iterator un = units.find(loc);
1710  const unit_map::const_iterator up = units.find(opp_loc);
1711  if(un == units.end() || up == units.end()) {
1712  return false;
1713  }
1714 
1715  unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon);
1716  for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
1717  const std::string& active_on = (*i->first)["active_on"];
1718  if(!(active_on.empty() || (attacker && active_on == "offense") || (!attacker && active_on == "defense")) || ability_apply_filter(un, up, ability, *i->first, loc, opp_loc, attacker)) {
1719  i = abil.erase(i);
1720  } else {
1721  ++i;
1722  }
1723  }
1724  if(!abil.empty()) {
1725  return true;
1726  }
1727  return false;
1728 }
1729 
1730 //emulate boolean special for self/adjacent and/or opponent.
1731 bool attack_type::bool_ability(const std::string& ability) const
1732 {
1733  bool abil_bool= get_special_bool(ability);
1734  const unit_map& units = display::get_singleton()->get_units();
1735 
1736  if(leadership_affects_self(ability, units, self_loc_, is_attacker_, shared_from_this(), other_attack_)) {
1737  abil_bool = get_special_bool(ability) || bool_leadership(ability, units, self_loc_, other_loc_, is_attacker_, shared_from_this(), other_attack_);
1738  }
1739 
1740  if(leadership_affects_opponent(ability, units, other_loc_, !is_attacker_, other_attack_, shared_from_this())) {
1741  abil_bool = get_special_bool(ability) || bool_leadership(ability, units, other_loc_, self_loc_, !is_attacker_, other_attack_, shared_from_this());
1742  }
1743  return abil_bool;
1744 }
1745 
1746 //emulate numerical special for self/adjacent and/or opponent.
1747 std::pair<int, bool> attack_type::combat_ability(const std::string& ability, int abil_value, bool backstab_pos) const
1748 {
1749  const unit_map& units = display::get_singleton()->get_units();
1750 
1751  if(leadership_affects_self(ability, units, self_loc_, is_attacker_, shared_from_this(), other_attack_)) {
1752  return ability_leadership(ability, units, self_loc_, other_loc_, is_attacker_, abil_value, backstab_pos, shared_from_this(), other_attack_);
1753  }
1754 
1755  if(leadership_affects_opponent(ability, units, other_loc_, !is_attacker_, other_attack_, shared_from_this())) {
1756  return ability_leadership(ability, units, other_loc_,self_loc_, !is_attacker_, abil_value, backstab_pos, other_attack_, shared_from_this());
1757  }
1758  return {abil_value, false};
1759 }
1760 //end of emulate weapon special functions.
1761 
1762 int combat_modifier(const unit_map& units,
1763  const gamemap& map,
1764  const map_location& loc,
1765  unit_type::ALIGNMENT alignment,
1766  bool is_fearless)
1767 {
1768  const tod_manager& tod_m = *resources::tod_manager;
1769  const time_of_day& effective_tod = tod_m.get_illuminated_time_of_day(units, map, loc);
1770  return combat_modifier(effective_tod, alignment, is_fearless);
1771 }
1772 
1773 int combat_modifier(const time_of_day& effective_tod,
1774  unit_type::ALIGNMENT alignment,
1775  bool is_fearless)
1776 {
1777  const tod_manager& tod_m = *resources::tod_manager;
1778  const int lawful_bonus = effective_tod.lawful_bonus;
1779  return generic_combat_modifier(lawful_bonus, alignment, is_fearless, tod_m.get_max_liminal_bonus());
1780 }
1781 
1782 int generic_combat_modifier(int lawful_bonus, unit_type::ALIGNMENT alignment, bool is_fearless, int max_liminal_bonus)
1783 {
1784  int bonus;
1785 
1786  switch(alignment.v) {
1787  case unit_type::ALIGNMENT::LAWFUL:
1788  bonus = lawful_bonus;
1789  break;
1790  case unit_type::ALIGNMENT::NEUTRAL:
1791  bonus = 0;
1792  break;
1793  case unit_type::ALIGNMENT::CHAOTIC:
1794  bonus = -lawful_bonus;
1795  break;
1796  case unit_type::ALIGNMENT::LIMINAL:
1797  bonus = std::max(0, max_liminal_bonus-std::abs(lawful_bonus));
1798  break;
1799  default:
1800  bonus = 0;
1801  }
1802 
1803  if(is_fearless) {
1804  bonus = std::max<int>(bonus, 0);
1805  }
1806 
1807  return bonus;
1808 }
1809 
1810 bool backstab_check(const map_location& attacker_loc,
1811  const map_location& defender_loc,
1812  const unit_map& units,
1813  const std::vector<team>& teams)
1814 {
1815  const unit_map::const_iterator defender = units.find(defender_loc);
1816  if(defender == units.end()) {
1817  return false; // No defender
1818  }
1819 
1821  get_adjacent_tiles(defender_loc, adj.data());
1822 
1823  unsigned i;
1824 
1825  for(i = 0; i < adj.size(); ++i) {
1826  if(adj[i] == attacker_loc) {
1827  break;
1828  }
1829  }
1830 
1831  if(i >= 6) {
1832  return false; // Attack not from adjacent location
1833  }
1834 
1835  const unit_map::const_iterator opp = units.find(adj[(i + 3) % 6]);
1836 
1837  // No opposite unit.
1838  if(opp == units.end()) {
1839  return false;
1840  }
1841 
1842  if(opp->incapacitated()) {
1843  return false;
1844  }
1845 
1846  // If sides aren't valid teams, then they are enemies.
1847  if(std::size_t(defender->side() - 1) >= teams.size() || std::size_t(opp->side() - 1) >= teams.size()) {
1848  return true;
1849  }
1850 
1851  // Defender and opposite are enemies.
1852  if(teams[defender->side() - 1].is_enemy(opp->side())) {
1853  return true;
1854  }
1855 
1856  // Defender and opposite are friends.
1857  return false;
1858 }
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:520
std::unique_ptr< combatant > attacker_combatant_
Outcome of simulated fight.
Definition: attack.hpp:256
const std::string & base_id() const
The id of the original type from which this (variation) descended.
Definition: types.hpp:142
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
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:420
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:1271
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:2998
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:99
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:834
unit_filter & set_use_flat_tod(bool value)
Definition: filter.hpp:121
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:1343
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:495
unit_race::GENDER gender() const
The gender of this unit.
Definition: unit.hpp:432
const combatant & get_attacker_combatant(const combatant *prev_def=nullptr)
Get the simulation results.
Definition: attack.cpp:456
#define a
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:466
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:1570
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:832
int experience_needed(bool with_acceleration=true) const
Definition: types.cpp:543
const unit_map & get_units() const
Definition: display.hpp:121
unit_type_data unit_types
Definition: types.cpp:1529
The unit is petrified - it cannot move or be attacked.
Definition: unit.hpp:833
int resistance_against(const std::string &damage_name, bool attacker) const
Gets resistance while considering custom WML abilities.
Definition: types.cpp:847
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 matches(const unit &u, const map_location &loc) const
Determine if *this matches filter at a specified location.
Definition: filter.hpp:129
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:1782
bool bool_leadership(const std::string &ability, const unit_map &units, const map_location &loc, const map_location &opp_loc, bool attacker, const_attack_ptr weapon, const_attack_ptr opp_weapon)
Definition: attack.cpp:1707
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
std::pair< int, bool > combat_ability(const std::string &ability, int abil_value=0, bool backstab_pos=false) const
Definition: attack.cpp:1747
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:442
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:155
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
bool filter_base_matches(const config &cfg, int def)
Definition: abilities.cpp:1256
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:316
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:463
Object which defines a time of day with associated bonuses, image, sounds etc.
Definition: time_of_day.hpp:57
bool bool_ability(const std::string &ability) const
Definition: attack.cpp:1731
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:1637
bool musthave_status(const std::string &status) const
Definition: types.cpp:699
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:940
void set_state(const std::string &state, bool value)
Set whether the unit is affected by a status effect.
Definition: unit.cpp:1391
#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:483
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:831
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:537
bool ability_filter_fighter(const std::string &ability, const std::string &filter_attacker, const config &cfg, const map_location &loc, const unit &u2) const
Definition: attack.cpp:1594
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:471
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:835
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:59
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:130
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:1810
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:1500
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:472
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:1551
#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:896
bool disable
Attack has disable special.
Definition: attack.hpp:66
bool firststrike
Attack has firststrike special.
Definition: attack.hpp:65
bool abilities_filter_matches(const config &cfg, bool attacker, int res) const
Definition: attack.cpp:1579
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:153
unit_ability_list get_abilities(const std::string &tag_name, const map_location &loc, const_attack_ptr weapon=nullptr, const_attack_ptr opp_weapon=nullptr) const
Gets the unit&#39;s active abilities of a particular type if it were on a specified location.
Definition: abilities.cpp:184
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:408
void advance_unit_at(const advance_unit_params &params)
bool leadership_affects_opponent(const std::string &ability, const unit_map &units, const map_location &loc, bool attacker, const_attack_ptr weapon, const_attack_ptr opp_weapon)
Definition: attack.cpp:1644
int hitpoints() const
Definition: types.hpp:150
variant a_
Definition: function.cpp:722
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
bool leadership_affects_self(const std::string &ability, const unit_map &units, const map_location &loc, bool attacker, const_attack_ptr weapon, const_attack_ptr opp_weapon)
Definition: attack.cpp:1620
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:550
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:591
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:1203
int experience() const
The current number of experience points this unit has.
Definition: unit.hpp:490
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:1541
void defend_result(hit_result res, int cth, int damage, int drain)
Definition: statistics.cpp:608
A variable-expanding proxy for the config class.
Definition: variable.hpp:44
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
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:395
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
std::pair< int, bool > ability_leadership(const std::string &ability, const unit_map &units, const map_location &loc, const map_location &opp_loc, bool attacker, int abil_value, bool backstab_pos, const_attack_ptr weapon, const_attack_ptr opp_weapon)
Definition: attack.cpp:1669
static bool ability_apply_filter(const unit_map::const_iterator un, const unit_map::const_iterator up, const std::string &ability, const config &cfg, const map_location &loc, const map_location &opp_loc, bool attacker)
Definition: attack.cpp:1603
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:1762