The Battle for Wesnoth  1.15.0-dev
unit.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  * Routines to manage units.
18  */
19 
20 #include "units/unit.hpp"
21 
22 #include "color.hpp"
23 #include "deprecation.hpp"
24 #include "display.hpp"
25 #include "formatter.hpp"
26 #include "formula/string_utils.hpp" // for VGETTEXT
27 #include "game_board.hpp" // for game_board
28 #include "game_config.hpp" // for add_color_info, etc
29 #include "game_data.hpp"
30 #include "game_errors.hpp" // for game_error
31 #include "game_events/manager.hpp" // for add_events
32 #include "preferences/game.hpp" // for encountered_units
33 #include "gettext.hpp" // for N_
34 #include "lexical_cast.hpp"
35 #include "log.hpp" // for LOG_STREAM, logger, etc
36 #include "map/map.hpp" // for gamemap
37 #include "random.hpp" // for generator, rng
38 #include "resources.hpp" // for units, gameboard, teams, etc
39 #include "scripting/game_lua_kernel.hpp" // for game_lua_kernel
40 #include "side_filter.hpp" // for side_filter
41 #include "synced_context.hpp"
42 #include "team.hpp" // for team, get_teams, etc
43 #include "terrain/filter.hpp" // for terrain_filter
44 #include "units/abilities.hpp" // for effect, filter_base_matches
45 #include "units/animation.hpp" // for unit_animation
46 #include "units/animation_component.hpp" // for unit_animation_component
47 #include "units/filter.hpp"
48 #include "units/formula_manager.hpp" // for unit_formula_manager
49 #include "units/id.hpp"
50 #include "units/map.hpp" // for unit_map, etc
51 #include "variable.hpp" // for vconfig, etc
52 #include "game_version.hpp"
53 
54 #include "utils/functional.hpp"
55 #include <boost/dynamic_bitset.hpp>
56 #include <boost/function_output_iterator.hpp>
57 
58 #ifdef _MSC_VER
59 #pragma warning (push)
60 #pragma warning (disable: 4510 4610)
61 #endif
62 #include <boost/range/algorithm.hpp>
63 #ifdef _MSC_VER
64 #pragma warning (pop)
65 #endif
66 
67 #include <array>
68 #include <cassert> // for assert
69 #include <cstdlib> // for rand
70 #include <exception> // for exception
71 #include <iterator> // for back_insert_iterator, etc
72 #include <new> // for operator new
73 #include <ostream> // for operator<<, basic_ostream, etc
74 
75 namespace t_translation { struct terrain_code; }
76 
77 static lg::log_domain log_unit("unit");
78 #define DBG_UT LOG_STREAM(debug, log_unit)
79 #define LOG_UT LOG_STREAM(info, log_unit)
80 #define WRN_UT LOG_STREAM(warn, log_unit)
81 #define ERR_UT LOG_STREAM(err, log_unit)
82 
83 namespace
84 {
85  // "advance" only kept around for backwards compatibility; only "advancement" should be used
86  const std::array<std::string, 4> ModificationTypes {{ "advancement", "advance", "trait", "object" }};
87 
88  /**
89  * Pointers to units which have data in their internal caches. The
90  * destructor of an unit removes itself from the cache, so the pointers are
91  * always valid.
92  */
93  static std::vector<const unit*> units_with_cache;
94 
95  static const std::string leader_crown_path = "misc/leader-crown.png";
96  static std::array<std::string, 60> internalized_attrs {{
97  "type",
98  "id",
99  "name",
100  "gender",
101  "random_gender",
102  "variation",
103  "role",
104  "ai_special",
105  "side",
106  "underlying_id",
107  "overlays",
108  "facing",
109  "race",
110  "level",
111  "recall_cost",
112  "undead_variation",
113  "max_attacks",
114  "attacks_left",
115  "alpha",
116  "zoc",
117  "flying",
118  "cost",
119  "max_hitpoints",
120  "max_moves",
121  "vision",
122  "jamming",
123  "max_experience",
124  "advances_to",
125  "hitpoints",
126  "goto_x",
127  "goto_y",
128  "moves",
129  "experience",
130  "resting",
131  "unrenamable",
132  "alignment",
133  "canrecruit",
134  "extra_recruit",
135  "x",
136  "y",
137  "placement",
138  "parent_type",
139  "description",
140  "usage",
141  "halo",
142  "ellipse",
143  "upkeep",
144  "random_traits",
145  "generate_name",
146  "profile",
147  "small_profile",
148  "fire_event",
149  "passable",
150  "overwrite",
151  "location_id",
152  "hidden",
153  // Useless attributes created when saving units to WML:
154  "flag_rgb",
155  "language_name",
156  "image",
157  "image_icon"
158  }};
159 
160  struct internalized_attrs_sorter
161  {
162  internalized_attrs_sorter()
163  {
164  std::sort(std::begin(internalized_attrs), std::end(internalized_attrs));
165  }
166  };
167 
168  // Sort the array to make set_difference below work.
169  internalized_attrs_sorter sorter;
170 
171  void warn_unknown_attribute(const config::const_attr_itors& cfg)
172  {
173  config::const_attribute_iterator cur = cfg.begin();
174  config::const_attribute_iterator end = cfg.end();
175 
176  auto cur_known = internalized_attrs.begin();
177  auto end_known = internalized_attrs.end();
178 
179  while(cur_known != end_known) {
180  if(cur == end) {
181  return;
182  }
183  int comp = cur->first.compare(*cur_known);
184  if(comp < 0) {
185  WRN_UT << "Unknown attribute '" << cur->first << "' discarded." << std::endl;
186  ++cur;
187  }
188  else if(comp == 0) {
189  ++cur;
190  ++cur_known;
191  }
192  else {
193  ++cur_known;
194  }
195  }
196 
197  while(cur != end) {
198  WRN_UT << "Unknown attribute '" << cur->first << "' discarded." << std::endl;
199  ++cur;
200  }
201  }
202 
203  template<typename T>
204  T* copy_or_null(const std::unique_ptr<T>& ptr)
205  {
206  return ptr ? new T(*ptr) : nullptr;
207  }
208 } // end anon namespace
209 
210 /**
211  * Intrusive Pointer interface
212  *
213  **/
214 
216 {
217  assert(u->ref_count_ >= 0);
218  // the next code line is to notice possible wrongly initialized units.
219  // The 100000 is picked rather randomly. If you are in the situation
220  // that you can actually have more then 100000 intrusive_ptr to one unit
221  // or if you are sure that the refcounting system works
222  // then feel free to remove the next line
223  assert(u->ref_count_ < 100000);
224  if(u->ref_count_ == 0) {
225  LOG_UT << "Freshly constructed" << std::endl;
226  }
227  ++(u->ref_count_);
228 }
229 
231 {
232  assert(u->ref_count_ >= 1);
233  assert(u->ref_count_ < 100000); //See comment in intrusive_ptr_add_ref
234  if(--(u->ref_count_) == 0)
235  {
236  DBG_UT << "Deleting a unit: id = " << u->id() << ", uid = " << u->underlying_id() << std::endl;
237  delete u;
238  }
239 }
240 
241 /**
242  * Converts a string ID to a unit_type.
243  * Throws a game_error exception if the string does not correspond to a type.
244  */
245 static const unit_type& get_unit_type(const std::string& type_id)
246 {
247  if(type_id.empty()) {
248  throw unit_type::error("creating unit with an empty type field");
249  }
250  std::string new_id = type_id;
251  unit_type::check_id(new_id);
252  const unit_type* i = unit_types.find(new_id);
253  if(!i) throw unit_type::error("unknown unit type: " + type_id);
254  return *i;
255 }
256 
257 static unit_race::GENDER generate_gender(const unit_type& type, bool random_gender)
258 {
259  const std::vector<unit_race::GENDER>& genders = type.genders();
260  assert(genders.size() > 0);
261 
262  if(random_gender == false || genders.size() == 1) {
263  return genders.front();
264  } else {
265  return genders[randomness::generator->get_random_int(0,genders.size()-1)];
266  // Note: genders is guaranteed to be non-empty, so this is not a
267  // potential division by zero.
268  // Note: Whoever wrote this code, you should have used an assertion, to save others hours of work...
269  // If the assertion size>0 is failing for you, one possible cause is that you are constructing a unit
270  // from a unit type which has not been ``built'' using the unit_type_data methods.
271  }
272 }
273 
274 static unit_race::GENDER generate_gender(const unit_type& u_type, const config& cfg)
275 {
276  const std::string& gender = cfg["gender"];
277  if(!gender.empty()) {
278  return string_gender(gender);
279  }
280 
281  return generate_gender(u_type, cfg["random_gender"].to_bool());
282 }
283 
285 {
286  ptr_vector_pushback(boost::ptr_vector<config>& vec) : vec_(&vec) {}
287 
288  void operator()(const config& cfg)
289  {
290  vec_->push_back(new config(cfg));
291  }
292 
293  //Don't use reference to be copyable.
294  boost::ptr_vector<config>* vec_;
295 };
296 
297 // Copy constructor
298 unit::unit(const unit& o)
299  : ref_count_(0)
300  , loc_(o.loc_)
301  , advances_to_(o.advances_to_)
302  , type_(o.type_)
303  , type_name_(o.type_name_)
304  , race_(o.race_)
305  , id_(o.id_)
306  , name_(o.name_)
307  , underlying_id_(o.underlying_id_)
308  , undead_variation_(o.undead_variation_)
309  , variation_(o.variation_)
310  , hit_points_(o.hit_points_)
311  , max_hit_points_(o.max_hit_points_)
312  , experience_(o.experience_)
313  , max_experience_(o.max_experience_)
314  , level_(o.level_)
315  , recall_cost_(o.recall_cost_)
316  , canrecruit_(o.canrecruit_)
317  , recruit_list_(o.recruit_list_)
318  , alignment_(o.alignment_)
319  , flag_rgb_(o.flag_rgb_)
320  , image_mods_(o.image_mods_)
321  , unrenamable_(o.unrenamable_)
322  , side_(o.side_)
323  , gender_(o.gender_)
324  , formula_man_(new unit_formula_manager(o.formula_manager()))
325  , movement_(o.movement_)
326  , max_movement_(o.max_movement_)
327  , vision_(o.vision_)
328  , jamming_(o.jamming_)
329  , movement_type_(o.movement_type_)
330  , hold_position_(o.hold_position_)
331  , end_turn_(o.end_turn_)
332  , resting_(o.resting_)
333  , attacks_left_(o.attacks_left_)
334  , max_attacks_(o.max_attacks_)
335  , states_(o.states_)
336  , known_boolean_states_(o.known_boolean_states_)
337  , variables_(o.variables_)
338  , events_(o.events_)
339  , filter_recall_(o.filter_recall_)
340  , emit_zoc_(o.emit_zoc_)
341  , overlays_(o.overlays_)
342  , role_(o.role_)
343  , attacks_(o.attacks_)
344  , facing_(o.facing_)
345  , trait_names_(o.trait_names_)
346  , trait_descriptions_(o.trait_descriptions_)
347  , unit_value_(o.unit_value_)
348  , goto_(o.goto_)
349  , interrupted_move_(o.interrupted_move_)
350  , is_fearless_(o.is_fearless_)
351  , is_healthy_(o.is_healthy_)
352  , modification_descriptions_(o.modification_descriptions_)
353  , anim_comp_(new unit_animation_component(*this, *o.anim_comp_))
354  , hidden_(o.hidden_)
355  , hp_bar_scaling_(o.hp_bar_scaling_)
356  , xp_bar_scaling_(o.xp_bar_scaling_)
357  , modifications_(o.modifications_)
358  , abilities_(o.abilities_)
359  , advancements_(o.advancements_)
360  , description_(o.description_)
361  , usage_(copy_or_null(o.usage_))
362  , halo_(copy_or_null(o.halo_))
363  , ellipse_(copy_or_null(o.ellipse_))
364  , random_traits_(o.random_traits_)
365  , generate_name_(o.generate_name_)
366  , upkeep_(o.upkeep_)
367  , profile_(o.profile_)
368  , small_profile_(o.small_profile_)
369  , invisibility_cache_()
370 {
371  // Copy the attacks rather than just copying references
372  for(auto& a : attacks_) {
373  a.reset(new attack_type(*a));
374  }
375 }
376 
378  : ref_count_(0)
379  , loc_()
380  , advances_to_()
381  , type_(nullptr)
382  , type_name_()
383  , race_(&unit_race::null_race)
384  , id_()
385  , name_()
386  , underlying_id_(0)
388  , variation_()
389  , hit_points_(1)
390  , max_hit_points_(1)
391  , experience_(0)
392  , max_experience_(1)
393  , level_(0)
394  , recall_cost_(-1)
395  , canrecruit_(false)
396  , recruit_list_()
397  , alignment_()
398  , flag_rgb_()
399  , image_mods_()
400  , unrenamable_(false)
401  , side_(0)
402  , gender_(unit_race::NUM_GENDERS)
404  , movement_(0)
405  , max_movement_(0)
406  , vision_(-1)
407  , jamming_(0)
408  , movement_type_()
409  , hold_position_(false)
410  , end_turn_(false)
411  , resting_(false)
412  , attacks_left_(0)
413  , max_attacks_(0)
414  , states_()
416  , variables_()
417  , events_()
418  , filter_recall_()
419  , emit_zoc_(0)
420  , overlays_()
421  , role_()
422  , attacks_()
423  , facing_(map_location::NDIRECTIONS)
424  , trait_names_()
426  , unit_value_()
427  , goto_()
429  , is_fearless_(false)
430  , is_healthy_(false)
433  , hidden_(false)
434  , hp_bar_scaling_(0)
435  , xp_bar_scaling_(0)
436  , modifications_()
437  , abilities_()
438  , advancements_()
439  , description_()
440  , usage_()
441  , halo_()
442  , ellipse_()
443  , random_traits_(true)
444  , generate_name_(true)
445  , upkeep_(upkeep_full())
447 {
448 
449 }
450 
451 void unit::init(const config& cfg, bool use_traits, const vconfig* vcfg)
452 {
453  loc_ = map_location(cfg["x"], cfg["y"], wml_loc());
454  type_ = &get_unit_type(cfg["parent_type"].blank() ? cfg["type"].str() : cfg["parent_type"].str());
456  id_ = cfg["id"].str();
457  name_ = cfg["name"].t_str();
458  variation_ = cfg["variation"].empty() ? type_->default_variation() : cfg["variation"].str();
459  canrecruit_ = cfg["canrecruit"].to_bool();
460  gender_ = generate_gender(*type_, cfg);
461  role_ = cfg["role"].str();
462  //, facing_(map_location::NDIRECTIONS)
463  //, anim_comp_(new unit_animation_component(*this))
464  hidden_ = cfg["hidden"].to_bool(false);
465  hp_bar_scaling_ = cfg["hp_bar_scaling"].blank() ? type_->hp_bar_scaling() : cfg["hp_bar_scaling"];
466  xp_bar_scaling_ = cfg["xp_bar_scaling"].blank() ? type_->xp_bar_scaling() : cfg["xp_bar_scaling"];
467  random_traits_ = true;
468  generate_name_ = true;
469  side_ = cfg["side"].to_int();
470 
471  if(side_ <= 0) {
472  side_ = 1;
473  }
474 
476  underlying_id_ = n_unit::unit_id(cfg["underlying_id"].to_size_t());
478 
479  overlays_ = utils::parenthetical_split(cfg["overlays"], ',');
480  if(overlays_.size() == 1 && overlays_.front().empty()) {
481  overlays_.clear();
482  }
483 
484  if(vcfg) {
485  const vconfig& filter_recall = vcfg->child("filter_recall");
486  if(!filter_recall.null())
487  filter_recall_ = filter_recall.get_config();
488 
489  const vconfig::child_list& events = vcfg->get_children("event");
490  for(const vconfig& e : events) {
491  events_.add_child("event", e.get_config());
492  }
493  } else {
494  filter_recall_ = cfg.child_or_empty("filter_recall");
495 
496  for(const config& unit_event : cfg.child_range("event")) {
497  events_.add_child("event", unit_event);
498  }
499  }
500 
503  }
504 
505  random_traits_ = cfg["random_traits"].to_bool(true);
506  facing_ = map_location::parse_direction(cfg["facing"]);
508 
509  if(const config& mods = cfg.child("modifications")) {
510  modifications_ = mods;
511  }
512 
513  generate_name_ = cfg["generate_name"].to_bool(true);
514 
515  // Apply the unit type's data to this unit.
516  advance_to(*type_, use_traits);
517 
518  if(const config& variables = cfg.child("variables")) {
520  }
521 
522  if(const config::attribute_value* v = cfg.get("race")) {
523  if(const unit_race *r = unit_types.find_race(*v)) {
524  race_ = r;
525  } else {
527  }
528  }
529 
530  level_ = cfg["level"].to_int(level_);
531 
532  if(const config::attribute_value* v = cfg.get("undead_variation")) {
533  undead_variation_ = v->str();
534  }
535 
536  if(const config::attribute_value* v = cfg.get("max_attacks")) {
537  max_attacks_ = std::max(0, v->to_int(1));
538  }
539 
540  attacks_left_ = std::max(0, cfg["attacks_left"].to_int(max_attacks_));
541 
542  if(const config::attribute_value* v = cfg.get("zoc")) {
543  emit_zoc_ = v->to_bool(level_ > 0);
544  }
545 
546  if(const config::attribute_value* v = cfg.get("description")) {
547  description_ = *v;
548  }
549 
550  if(const config::attribute_value* v = cfg.get("cost")) {
551  unit_value_ = *v;
552  }
553 
554  if(const config::attribute_value* v = cfg.get("ellipse")) {
555  set_image_ellipse(*v);
556  }
557 
558  if(const config::attribute_value* v = cfg.get("halo")) {
559  set_image_halo(*v);
560  }
561 
562  if(const config::attribute_value* v = cfg.get("usage")) {
563  set_usage(*v);
564  }
565 
566  if(const config::attribute_value* v = cfg.get("profile")) {
567  std::string profile = (*v).str();
568  adjust_profile(profile);
569  profile_ = profile;
570  }
571 
572  if(const config::attribute_value* v = cfg.get("small_profile")) {
573  small_profile_ = (*v).str();
574  }
575 
576  max_hit_points_ = std::max(1, cfg["max_hitpoints"].to_int(max_hit_points_));
577  max_movement_ = std::max(0, cfg["max_moves"].to_int(max_movement_));
578  max_experience_ = std::max(1, cfg["max_experience"].to_int(max_experience_));
579 
580  vision_ = cfg["vision"].to_int(vision_);
581  jamming_ = cfg["jamming"].to_int(jamming_);
582 
583  std::vector<std::string> temp_advances = utils::split(cfg["advances_to"]);
584  if(temp_advances.size() == 1 && temp_advances.front() == "null") {
585  advances_to_.clear();
586  } else if(temp_advances.size() >= 1 && !temp_advances.front().empty()) {
587  advances_to_ = temp_advances;
588  }
589 
590  if(const config& ai = cfg.child("ai")) {
591  formula_man_->read(ai);
592  }
593 
594  // Don't use the unit_type's attacks if this config has its own defined
595  if(config::const_child_itors cfg_range = cfg.child_range("attack")) {
596  attacks_.clear();
597  for(const config& c : cfg_range) {
598  attacks_.emplace_back(new attack_type(c));
599  }
600  }
601 
602  // If cfg specifies [advancement]s, replace this [advancement]s with them.
603  if(cfg.has_child("advancement")) {
604  this->advancements_.clear();
605  boost::copy(cfg.child_range("advancement"), boost::make_function_output_iterator(ptr_vector_pushback(advancements_)));
606  }
607 
608  // Don't use the unit_type's abilities if this config has its own defined
609  // Why do we allow multiple [abilities] tags?
610  if(config::const_child_itors cfg_range = cfg.child_range("abilities")) {
611  abilities_.clear();
612  for(const config& abilities : cfg_range) {
613  this->abilities_.append(abilities);
614  }
615  }
616 
617  // Adjust the unit's defense, movement, vision, jamming, resistances, and
618  // flying status if this config has its own defined.
619  movement_type_.merge(cfg);
620 
621  if(const config& status_flags = cfg.child("status")) {
622  for(const config::attribute &st : status_flags.attribute_range()) {
623  if(st.second.to_bool()) {
624  set_state(st.first, true);
625  }
626  }
627  }
628 
629  if(cfg["ai_special"] == "guardian") {
630  set_state(STATE_GUARDIAN, true);
631  }
632 
633  if(const config::attribute_value* v = cfg.get("hitpoints")) {
634  hit_points_ = *v;
635  } else {
637  }
638 
639  if(const config::attribute_value* v = cfg.get("invulnerable")) {
640  set_state("invulnerable", v->to_bool());
641  }
642 
643  goto_.set_wml_x(cfg["goto_x"].to_int());
644  goto_.set_wml_y(cfg["goto_y"].to_int());
645 
646  if(const config::attribute_value* v = cfg.get("moves")) {
647  movement_ = *v;
648  if(movement_ < 0) {
649  attacks_left_ = 0;
650  movement_ = 0;
651  }
652  } else {
654  }
655 
656  experience_ = cfg["experience"];
657  resting_ = cfg["resting"].to_bool();
658  unrenamable_ = cfg["unrenamable"].to_bool();
659 
660  // We need to check to make sure that the cfg is not blank and if it
661  // isn't pull that value otherwise it goes with the default of -1.
662  if(!cfg["recall_cost"].blank()) {
663  recall_cost_ = cfg["recall_cost"].to_int(recall_cost_);
664  }
665 
666  alignment_.parse(cfg["alignment"].str());
667 
668  generate_name();
669 
670  parse_upkeep(cfg["upkeep"]);
671 
672  set_recruits(utils::split(cfg["extra_recruit"]));
673 
675  warn_unknown_attribute(cfg.attribute_range());
676 
677 #if 0
678  // Debug unit animations for units as they appear in game
679  for(const auto& anim : anim_comp_->animations_) {
680  std::cout << anim.debug() << std::endl;
681  }
682 #endif
683 }
684 
686 {
687  for(auto& u : units_with_cache) {
688  u->clear_visibility_cache();
689  }
690 
691  units_with_cache.clear();
692 }
693 
694 void unit::init(const unit_type& u_type, int side, bool real_unit, unit_race::GENDER gender)
695 {
696  type_ = &u_type;
699  side_ = side;
700  gender_ = gender != unit_race::NUM_GENDERS ? gender : generate_gender(u_type, real_unit);
702  upkeep_ = upkeep_full();
703 
704  // Apply the unit type's data to this unit.
705  advance_to(u_type, real_unit);
706 
707  if(real_unit) {
708  generate_name();
709  }
710 
712 
713  // Set these after traits and modifications have set the maximums.
717 }
718 
720 {
721  try {
722  anim_comp_->clear_haloes();
723 
724  // Remove us from the status cache
725  auto itor = std::find(units_with_cache.begin(), units_with_cache.end(), this);
726 
727  if(itor != units_with_cache.end()) {
728  units_with_cache.erase(itor);
729  }
730  } catch(const std::exception & e) {
731  ERR_UT << "Caught exception when destroying unit: " << e.what() << std::endl;
732  } catch(...) {}
733 }
734 
735 /**
736  * Swap, for copy and swap idiom
737  */
738 void unit::swap(unit & o)
739 {
740  using std::swap;
741 
742  // Don't swap reference count, or it will be incorrect...
743  swap(loc_, o.loc_);
745  swap(type_, o.type_);
747  swap(race_, o.race_);
748  swap(id_, o.id_);
749  swap(name_, o.name_);
757  swap(level_, o.level_);
765  swap(side_, o.side_);
766  swap(gender_, o.gender_);
770  swap(vision_, o.vision_);
771  swap(jamming_, o.jamming_);
775  swap(resting_, o.resting_);
778  swap(states_, o.states_);
781  swap(events_, o.events_);
785  swap(role_, o.role_);
786  swap(attacks_, o.attacks_);
787  swap(facing_, o.facing_);
791  swap(goto_, o.goto_);
797  swap(hidden_, o.hidden_);
800 }
801 
803 {
804  if(!name_.empty() || !generate_name_) {
805  return;
806  }
808  generate_name_ = false;
809 }
810 
811 void unit::generate_traits(bool must_have_only)
812 {
813  LOG_UT << "Generating a trait for unit type " << type().log_id() << " with must_have_only " << must_have_only << std::endl;
814  const unit_type& u_type = type();
815 
816  // Calculate the unit's traits
817  config::const_child_itors current_traits = modifications_.child_range("trait");
818  std::vector<const config*> candidate_traits;
819 
820  for(const config& t : u_type.possible_traits()) {
821  // Skip the trait if the unit already has it.
822  const std::string& tid = t["id"];
823  bool already = false;
824  for(const config& mod : current_traits) {
825  if(mod["id"] == tid) {
826  already = true;
827  break;
828  }
829  }
830 
831  if(already) {
832  continue;
833  }
834 
835  // Add the trait if it is mandatory.
836  const std::string& avl = t["availability"];
837  if(avl == "musthave") {
838  modifications_.add_child("trait", t);
839  current_traits = modifications_.child_range("trait");
840  continue;
841  }
842 
843  // The trait is still available, mark it as a candidate for randomizing.
844  // For leaders, only traits with availability "any" are considered.
845  if(!must_have_only && (!can_recruit() || avl == "any")) {
846  candidate_traits.push_back(&t);
847  }
848  }
849 
850  if(must_have_only) return;
851 
852  // Now randomly fill out to the number of traits required or until
853  // there aren't any more traits.
854  int nb_traits = current_traits.size();
855  int max_traits = u_type.num_traits();
856  for(; nb_traits < max_traits && !candidate_traits.empty(); ++nb_traits)
857  {
858  int num = randomness::generator->get_random_int(0,candidate_traits.size()-1);
859  modifications_.add_child("trait", *candidate_traits[num]);
860  candidate_traits.erase(candidate_traits.begin() + num);
861  }
862 
863  // Once random traits are added, don't do it again.
864  // Such as when restoring a saved character.
865  random_traits_ = false;
866 }
867 
868 std::vector<std::string> unit::get_traits_list() const
869 {
870  std::vector<std::string> res;
871 
872  for(const config& mod : modifications_.child_range("trait"))
873  {
874  // Make sure to return empty id trait strings as otherwise
875  // names will not match in length (Bug #21967)
876  res.push_back(mod["id"]);
877  }
878  return res;
879 }
880 
881 
882 /**
883  * Advances this unit to the specified type.
884  * Experience is left unchanged.
885  * Current hit point total is left unchanged unless it would violate max HP.
886  * Assumes gender_ and variation_ are set to their correct values.
887  */
888 void unit::advance_to(const unit_type& u_type, bool use_traits)
889 {
890  appearance_changed_ = true;
891  // For reference, the type before this advancement.
892  const unit_type& old_type = type();
893  // Adjust the new type for gender and variation.
895 
896  // Reset the scalar values first
897  trait_names_.clear();
898  trait_descriptions_.clear(),
899  is_fearless_ = false;
900  is_healthy_ = false;
901 
902  // Clear modification-related caches
904 
905  // build unit type ready to create units. Not sure if needed.
906  new_type.get_cfg_for_units();
907 
908  if(!new_type.usage().empty()) {
909  set_usage(new_type.usage());
910  }
911 
912  set_image_halo(new_type.halo());
913  if(!new_type.ellipse().empty()) {
914  set_image_ellipse(new_type.ellipse());
915  }
916 
917  generate_name_ &= new_type.generate_name();
918  abilities_ = new_type.abilities_cfg();
919  advancements_.clear();
920 
921  for(const config& advancement : new_type.advancements()) {
922  advancements_.push_back(new config(advancement));
923  }
924 
925  // If unit has specific profile, remember it and keep it after advancing
926  if(small_profile_.empty() || small_profile_ == old_type.small_profile()) {
927  small_profile_ = new_type.small_profile();
928  }
929 
930  if(profile_.empty() || profile_ == old_type.big_profile()) {
931  profile_ = new_type.big_profile();
932  }
933  // NOTE: There should be no need to access old_cfg (or new_cfg) after this
934  // line. Particularly since the swap might have affected old_cfg.
935 
936  advances_to_ = new_type.advances_to();
937 
938  race_ = new_type.race();
939  type_ = &new_type;
940  type_name_ = new_type.type_name();
941  description_ = new_type.unit_description();
942  undead_variation_ = new_type.undead_variation();
943  max_experience_ = new_type.experience_needed(false);
944  level_ = new_type.level();
945  recall_cost_ = new_type.recall_cost();
946  alignment_ = new_type.alignment();
947  max_hit_points_ = new_type.hitpoints();
948  hp_bar_scaling_ = new_type.hp_bar_scaling();
949  xp_bar_scaling_ = new_type.xp_bar_scaling();
950  max_movement_ = new_type.movement();
951  vision_ = new_type.vision(true);
952  jamming_ = new_type.jamming();
953  movement_type_ = new_type.movement_type();
954  emit_zoc_ = new_type.has_zoc();
955  attacks_.clear();
956  std::transform(new_type.attacks().begin(), new_type.attacks().end(), std::back_inserter(attacks_), [](const attack_type& atk) {
957  return std::make_shared<attack_type>(atk);
958  });
959  unit_value_ = new_type.cost();
960 
961  max_attacks_ = new_type.max_attacks();
962 
963  flag_rgb_ = new_type.flag_rgb();
964 
965  upkeep_ = upkeep_full();
966  parse_upkeep(new_type.get_cfg()["upkeep"]);
967 
968  anim_comp_->reset_after_advance(&new_type);
969 
970  if(random_traits_) {
971  generate_traits(!use_traits);
972  } else {
973  // This will add any "musthave" traits to the new unit that it doesn't already have.
974  // This covers the Dark Sorcerer advancing to Lich and gaining the "undead" trait,
975  // but random and/or optional traits are not added,
976  // and neither are inappropriate traits removed.
977  generate_traits(true);
978  }
979 
980  // Apply modifications etc, refresh the unit.
981  // This needs to be after type and gender are fixed,
982  // since there can be filters on the modifications
983  // that may result in different effects after the advancement.
985 
986  // Now that modifications are done modifying traits, check if poison should
987  // be cleared.
988  if(get_state("unpoisonable")) {
989  set_state(STATE_POISONED, false);
990  }
991 
992  // Now that modifications are done modifying the maximum hit points,
993  // enforce this maximum.
996  }
997 
998  // In case the unit carries EventWML, apply it now
1000  resources::game_events->add_events(new_type.events(), new_type.id());
1001  }
1002 }
1003 
1004 std::string unit::big_profile() const
1005 {
1006  if(!profile_.empty() && profile_ != "unit_image") {
1007  return profile_;
1008  }
1009 
1010  return absolute_image();
1011 }
1012 
1013 std::string unit::small_profile() const
1014 {
1015  if(!small_profile_.empty() && small_profile_ != "unit_image") {
1016  return small_profile_;
1017  }
1018 
1019  if(!profile_.empty() && small_profile_ != "unit_image" && profile_ != "unit_image") {
1020  return profile_;
1021  }
1022 
1023  return absolute_image();
1024 }
1025 
1026 const std::string& unit::leader_crown()
1027 {
1028  return leader_crown_path;
1029 }
1030 
1031 const std::string& unit::flag_rgb() const
1032 {
1033  return flag_rgb_.empty() ? game_config::unit_rgb : flag_rgb_;
1034 }
1035 
1037 {
1038  double unit_energy = 0.0;
1039  color_t energy_color {0,0,0,255};
1040 
1041  if(max_hitpoints > 0) {
1042  unit_energy = static_cast<double>(hitpoints)/static_cast<double>(max_hitpoints);
1043  }
1044 
1045  if(1.0 == unit_energy) {
1046  energy_color.r = 33;
1047  energy_color.g = 225;
1048  energy_color.b = 0;
1049  } else if(unit_energy > 1.0) {
1050  energy_color.r = 100;
1051  energy_color.g = 255;
1052  energy_color.b = 100;
1053  } else if(unit_energy >= 0.75) {
1054  energy_color.r = 170;
1055  energy_color.g = 255;
1056  energy_color.b = 0;
1057  } else if(unit_energy >= 0.5) {
1058  energy_color.r = 255;
1059  energy_color.g = 175;
1060  energy_color.b = 0;
1061  } else if(unit_energy >= 0.25) {
1062  energy_color.r = 255;
1063  energy_color.g = 155;
1064  energy_color.b = 0;
1065  } else {
1066  energy_color.r = 255;
1067  energy_color.g = 0;
1068  energy_color.b = 0;
1069  }
1070 
1071  return energy_color;
1072 }
1073 
1075 {
1076  return hp_color_impl(hitpoints(), max_hitpoints());
1077 }
1078 
1079 color_t unit::hp_color(int new_hitpoints) const
1080 {
1081  return hp_color_impl(new_hitpoints, hitpoints());
1082 }
1083 
1085 {
1086  const color_t near_advance_color {255,255,255,255};
1087  const color_t mid_advance_color {150,255,255,255};
1088  const color_t far_advance_color {0,205,205,255};
1089  const color_t normal_color {0,160,225,255};
1090  const color_t near_amla_color {225,0,255,255};
1091  const color_t mid_amla_color {169,30,255,255};
1092  const color_t far_amla_color {139,0,237,255};
1093  const color_t amla_color {170,0,255,255};
1094 
1095  const bool near_advance = static_cast<int>(experience_to_advance()) <= game_config::kill_experience;
1096  const bool mid_advance = static_cast<int>(experience_to_advance()) <= game_config::kill_experience*2;
1097  const bool far_advance = static_cast<int>(experience_to_advance()) <= game_config::kill_experience*3;
1098 
1099  color_t color = normal_color;
1100  bool major_amla = false;
1101  for(const config& adv:get_modification_advances()){
1102  major_amla |= adv["major_amla"].to_bool();
1103  }
1104  if(advances_to().size() ||major_amla){
1105  if(near_advance){
1106  color=near_advance_color;
1107  } else if(mid_advance){
1108  color=mid_advance_color;
1109  } else if(far_advance){
1110  color=far_advance_color;
1111  }
1112  } else if(get_modification_advances().size()){
1113  if(near_advance){
1114  color=near_amla_color;
1115  } else if(mid_advance){
1116  color=mid_amla_color;
1117  } else if(far_advance){
1118  color=far_amla_color;
1119  } else {
1120  color=amla_color;
1121  }
1122  }
1123 
1124  return(color);
1125 }
1126 
1127 void unit::set_recruits(const std::vector<std::string>& recruits)
1128 {
1129  unit_types.check_types(recruits);
1131  //TODO crab
1132  //info_.minimum_recruit_price = 0;
1133  //ai::manager::get_singleton().raise_recruit_list_changed();
1134 }
1135 
1136 const std::vector<std::string> unit::advances_to_translated() const
1137 {
1138  std::vector<std::string> result;
1139  for(const std::string& adv_type_id : advances_to_) {
1140  if(const unit_type* adv_type = unit_types.find(adv_type_id)) {
1141  result.push_back(adv_type->type_name());
1142  } else {
1143  WRN_UT << "unknown unit in advances_to list of type "
1144  << type().log_id() << ": " << adv_type_id << std::endl;
1145  }
1146  }
1147 
1148  return result;
1149 }
1150 
1151 void unit::set_advances_to(const std::vector<std::string>& advances_to)
1152 {
1153  unit_types.check_types(advances_to);
1155 }
1156 
1157 void unit::set_movement(int moves, bool unit_action)
1158 {
1159  // If this was because the unit acted, clear its "not acting" flags.
1160  if(unit_action) {
1161  end_turn_ = hold_position_ = false;
1162  }
1163 
1164  movement_ = std::max<int>(0, moves);
1165 }
1166 
1167 /**
1168  * Determines if @a mod_dur "matches" @a goal_dur.
1169  * If goal_dur is not empty, they match if they are equal.
1170  * If goal_dur is empty, they match if mod_dur is neither empty nor "forever".
1171  * Helper function for expire_modifications().
1172  */
1173 inline bool mod_duration_match(const std::string& mod_dur, const std::string& goal_dur)
1174 {
1175  if(goal_dur.empty()) {
1176  // Default is all temporary modifications.
1177  return !mod_dur.empty() && mod_dur != "forever";
1178  }
1179 
1180  return mod_dur == goal_dur;
1181 }
1182 
1183 void unit::expire_modifications(const std::string& duration)
1184 {
1185  // If any modifications expire, then we will need to rebuild the unit.
1186  const unit_type* rebuild_from = nullptr;
1187  int hp = hit_points_;
1188  // Loop through all types of modifications.
1189  for(const auto& mod_name : ModificationTypes) {
1190  // Loop through all modifications of this type.
1191  // Looping in reverse since we may delete the current modification.
1192  for(int j = modifications_.child_count(mod_name)-1; j >= 0; --j)
1193  {
1194  const config& mod = modifications_.child(mod_name, j);
1195 
1196  if(mod_duration_match(mod["duration"], duration)) {
1197  // If removing this mod means reverting the unit's type:
1198  if(const config::attribute_value* v = mod.get("prev_type")) {
1199  rebuild_from = &get_unit_type(v->str());
1200  }
1201  // Else, if we have not already specified a type to build from:
1202  else if(rebuild_from == nullptr) {
1203  rebuild_from = &type();
1204  }
1205 
1206  modifications_.remove_child(mod_name, j);
1207  }
1208  }
1209  }
1210 
1211  if(rebuild_from != nullptr) {
1212  anim_comp_->clear_haloes();
1213  advance_to(*rebuild_from);
1214  hit_points_ = hp;
1215  }
1216 }
1217 
1219 {
1220  expire_modifications("turn");
1221 
1225  set_state(STATE_UNCOVERED, false);
1226 }
1227 
1229 {
1230  expire_modifications("turn end");
1231 
1232  set_state(STATE_SLOWED,false);
1234  resting_ = false;
1235  }
1236 
1237  set_state(STATE_NOT_MOVED,false);
1238  // Clear interrupted move
1240 }
1241 
1243 {
1244  // Set the goto-command to be going to no-where
1245  goto_ = map_location();
1246 
1247  // Expire all temporary modifications.
1249 
1250  heal_fully();
1251  set_state(STATE_SLOWED, false);
1252  set_state(STATE_POISONED, false);
1253  set_state(STATE_PETRIFIED, false);
1254  set_state(STATE_GUARDIAN, false);
1255 }
1256 
1257 void unit::heal(int amount)
1258 {
1259  int max_hp = max_hitpoints();
1260  if(hit_points_ < max_hp) {
1261  hit_points_ += amount;
1262 
1263  if(hit_points_ > max_hp) {
1264  hit_points_ = max_hp;
1265  }
1266  }
1267 
1268  if(hit_points_<1) {
1269  hit_points_ = 1;
1270  }
1271 }
1272 
1273 const std::set<std::string> unit::get_states() const
1274 {
1275  std::set<std::string> all_states = states_;
1276  for(const auto& state : known_boolean_state_names_) {
1277  if(get_state(state.second)) {
1278  all_states.insert(state.first);
1279  }
1280  }
1281 
1282  // Backwards compatibility for not_living. Don't remove before 1.12
1283  if(all_states.count("undrainable") && all_states.count("unpoisonable") && all_states.count("unplagueable")) {
1284  all_states.insert("not_living");
1285  }
1286 
1287  return all_states;
1288 }
1289 
1290 bool unit::get_state(const std::string& state) const
1291 {
1292  state_t known_boolean_state_id = get_known_boolean_state_id(state);
1293  if(known_boolean_state_id!=STATE_UNKNOWN){
1294  return get_state(known_boolean_state_id);
1295  }
1296 
1297  // Backwards compatibility for not_living. Don't remove before 1.12
1298  if(state == "not_living") {
1299  return
1300  get_state("undrainable") &&
1301  get_state("unpoisonable") &&
1302  get_state("unplagueable");
1303  }
1304 
1305  return states_.find(state) != states_.end();
1306 }
1307 
1308 void unit::set_state(state_t state, bool value)
1309 {
1310  known_boolean_states_[state] = value;
1311 }
1312 
1313 bool unit::get_state(state_t state) const
1314 {
1315  return known_boolean_states_[state];
1316 }
1317 
1319 {
1320  auto i = known_boolean_state_names_.find(state);
1321  if(i != known_boolean_state_names_.end()) {
1322  return i->second;
1323  }
1324 
1325  return STATE_UNKNOWN;
1326 }
1327 
1328 std::map<std::string, unit::state_t> unit::known_boolean_state_names_ {
1329  {"slowed", STATE_SLOWED},
1330  {"poisoned", STATE_POISONED},
1331  {"petrified", STATE_PETRIFIED},
1332  {"uncovered", STATE_UNCOVERED},
1333  {"not_moved", STATE_NOT_MOVED},
1334  {"unhealable", STATE_UNHEALABLE},
1335  {"guardian", STATE_GUARDIAN},
1336 };
1337 
1338 void unit::set_state(const std::string& state, bool value)
1339 {
1340  appearance_changed_ = true;
1341  state_t known_boolean_state_id = get_known_boolean_state_id(state);
1342  if(known_boolean_state_id != STATE_UNKNOWN) {
1343  set_state(known_boolean_state_id, value);
1344  return;
1345  }
1346 
1347  // Backwards compatibility for not_living. Don't remove before 1.12
1348  if(state == "not_living") {
1349  set_state("undrainable", value);
1350  set_state("unpoisonable", value);
1351  set_state("unplagueable", value);
1352  }
1353 
1354  if(value) {
1355  states_.insert(state);
1356  } else {
1357  states_.erase(state);
1358  }
1359 }
1360 
1361 bool unit::has_ability_by_id(const std::string& ability) const
1362 {
1363  for(const config::any_child &ab : this->abilities_.all_children_range()) {
1364  if(ab.cfg["id"] == ability) {
1365  return true;
1366  }
1367  }
1368 
1369  return false;
1370 }
1371 
1372 void unit::remove_ability_by_id(const std::string& ability)
1373 {
1375  while (i != this->abilities_.ordered_end()) {
1376  if(i->cfg["id"] == ability) {
1377  i = this->abilities_.erase(i);
1378  } else {
1379  ++i;
1380  }
1381  }
1382 }
1383 
1384 void unit::write(config& cfg) const
1385 {
1386  config back;
1387  auto write_subtag = [&](const std::string& key, const config& child)
1388  {
1389  cfg.clear_children(key);
1390 
1391  if(!child.empty()) {
1392  cfg.add_child(key, child);
1393  } else {
1394  back.add_child(key, child);
1395  }
1396  };
1397 
1398  movement_type_.write(cfg);
1399  cfg["small_profile"] = small_profile_;
1400  cfg["profile"] = profile_;
1401 
1402  if(description_ != type().unit_description()) {
1403  cfg["description"] = description_;
1404  }
1405 
1406  if(halo_.get()) {
1407  cfg["halo"] = *halo_;
1408  }
1409 
1410  if(ellipse_.get()) {
1411  cfg["ellipse"] = *ellipse_;
1412  }
1413 
1414  if(usage_.get()) {
1415  cfg["usage"] = *usage_;
1416  }
1417 
1418  write_upkeep(cfg["upkeep"]);
1419 
1420  cfg["hitpoints"] = hit_points_;
1421  cfg["max_hitpoints"] = max_hit_points_;
1422 
1423  cfg["image_icon"] = type().icon();
1424  cfg["image"] = type().image();
1425  cfg["random_traits"] = random_traits_;
1426  cfg["generate_name"] = generate_name_;
1427  cfg["experience"] = experience_;
1428  cfg["max_experience"] = max_experience_;
1429  cfg["recall_cost"] = recall_cost_;
1430 
1431  cfg["side"] = side_;
1432 
1433  cfg["type"] = type_id();
1434 
1435  if(type_id() != type().base_id()) {
1436  cfg["parent_type"] = type().base_id();
1437  }
1438 
1439  // Support for unit formulas in [ai] and unit-specific variables in [ai] [vars]
1440  formula_man_->write(cfg);
1441 
1442  cfg["gender"] = gender_string(gender_);
1443  cfg["variation"] = variation_;
1444  cfg["role"] = role_;
1445 
1446  config status_flags;
1447  for(const std::string& state : get_states()) {
1448  status_flags[state] = true;
1449  }
1450 
1451  write_subtag("variables", variables_);
1452  write_subtag("filter_recall", filter_recall_);
1453  write_subtag("status", status_flags);
1454 
1455  cfg.clear_children("events");
1456  cfg.append(events_);
1457 
1458  cfg["overlays"] = utils::join(overlays_);
1459 
1460  cfg["name"] = name_;
1461  cfg["id"] = id_;
1462  cfg["underlying_id"] = underlying_id_.value;
1463 
1464  if(can_recruit()) {
1465  cfg["canrecruit"] = true;
1466  }
1467 
1468  cfg["extra_recruit"] = utils::join(recruit_list_);
1469 
1470  cfg["facing"] = map_location::write_direction(facing_);
1471 
1472  cfg["goto_x"] = goto_.wml_x();
1473  cfg["goto_y"] = goto_.wml_y();
1474 
1475  cfg["moves"] = movement_;
1476  cfg["max_moves"] = max_movement_;
1477  cfg["vision"] = vision_;
1478  cfg["jamming"] = jamming_;
1479 
1480  cfg["resting"] = resting_;
1481 
1482  cfg["advances_to"] = utils::join(advances_to_);
1483 
1484  cfg["race"] = race_->id();
1485  cfg["language_name"] = type_name_;
1486  cfg["undead_variation"] = undead_variation_;
1487  cfg["level"] = level_;
1488  cfg["alignment"] = alignment_.to_string();
1489  cfg["flag_rgb"] = flag_rgb_;
1490  cfg["unrenamable"] = unrenamable_;
1491 
1492  cfg["attacks_left"] = attacks_left_;
1493  cfg["max_attacks"] = max_attacks_;
1494  cfg["zoc"] = emit_zoc_;
1495 
1496  cfg["hidden"] = hidden_;
1497 
1498  cfg.clear_children("attack");
1499  for(attack_ptr i : attacks_) {
1500  i->write(cfg.add_child("attack"));
1501  }
1502 
1503  cfg["cost"] = unit_value_;
1504 
1505  write_subtag("modifications", modifications_);
1506  write_subtag("abilities", abilities_);
1507 
1508  cfg.clear_children("advancement");
1509  for(const config& advancement : this->advancements_) {
1510  if(!advancement.empty()) {
1511  cfg.add_child("advancement", advancement);
1512  }
1513  }
1514  cfg.append(back);
1515 }
1516 
1518 {
1519  if(dir != map_location::NDIRECTIONS) {
1520  appearance_changed_ = true;
1521  facing_ = dir;
1522  }
1523  // Else look at yourself (not available so continue to face the same direction)
1524 }
1525 
1526 int unit::upkeep() const
1527 {
1528  // Leaders do not incur upkeep.
1529  if(can_recruit()) {
1530  return 0;
1531  }
1532 
1534 }
1535 
1536 bool unit::loyal() const
1537 {
1538  return boost::get<upkeep_loyal>(&upkeep_) != nullptr;
1539 }
1540 
1542 {
1543  int def = movement_type_.defense_modifier(terrain);
1544 #if 0
1545  // A [defense] ability is too costly and doesn't take into account target locations.
1546  // Left as a comment in case someone ever wonders why it isn't a good idea.
1547  unit_ability_list defense_abilities = get_abilities("defense");
1548  if(!defense_abilities.empty()) {
1549  unit_abilities::effect defense_effect(defense_abilities, def, false);
1550  def = defense_effect.get_composite_value();
1551  }
1552 #endif
1553  return def;
1554 }
1555 
1556 bool unit::resistance_filter_matches(const config& cfg, bool attacker, const std::string& damage_name, int res) const
1557 {
1558  if(!(cfg["active_on"].empty() || (attacker && cfg["active_on"] == "offense") || (!attacker && cfg["active_on"] == "defense"))) {
1559  return false;
1560  }
1561 
1562  const std::string& apply_to = cfg["apply_to"];
1563  if(!apply_to.empty()) {
1564  if(damage_name != apply_to) {
1565  if(apply_to.find(',') != std::string::npos &&
1566  apply_to.find(damage_name) != std::string::npos) {
1567  const std::vector<std::string>& vals = utils::split(apply_to);
1568  if(std::find(vals.begin(),vals.end(),damage_name) == vals.end()) {
1569  return false;
1570  }
1571  } else {
1572  return false;
1573  }
1574  }
1575  }
1576 
1577  if(!unit_abilities::filter_base_matches(cfg, res)) {
1578  return false;
1579  }
1580 
1581  return true;
1582 }
1583 
1584 int unit::resistance_against(const std::string& damage_name,bool attacker,const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon) const
1585 {
1586  int res = movement_type_.resistance_against(damage_name);
1587 
1588  unit_ability_list resistance_abilities = get_abilities("resistance",loc, weapon, opp_weapon);
1589  for(unit_ability_list::iterator i = resistance_abilities.begin(); i != resistance_abilities.end();) {
1590  if(!resistance_filter_matches(*i->first, attacker, damage_name, 100-res)) {
1591  i = resistance_abilities.erase(i);
1592  } else {
1593  ++i;
1594  }
1595  }
1596 
1597  if(!resistance_abilities.empty()) {
1598  unit_abilities::effect resist_effect(resistance_abilities, 100-res, false);
1599 
1600  res = 100 - std::min<int>(
1601  resist_effect.get_composite_value(),
1602  resistance_abilities.highest("max_value").first
1603  );
1604  }
1605 
1606  return res;
1607 }
1608 
1609 std::map<std::string, std::string> unit::advancement_icons() const
1610 {
1611  std::map<std::string,std::string> temp;
1612  if(!can_advance()) {
1613  return temp;
1614  }
1615 
1616  if(!advances_to_.empty()) {
1617  std::ostringstream tooltip;
1618  const std::string& image = game_config::images::level;
1619 
1620  for(const std::string& s : advances_to()) {
1621  if(!s.empty()) {
1622  tooltip << s << std::endl;
1623  }
1624  }
1625 
1626  temp[image] = tooltip.str();
1627  }
1628 
1629  for(const config& adv : get_modification_advances()) {
1630  const std::string& image = adv["image"];
1631  if(image.empty()) {
1632  continue;
1633  }
1634 
1635  std::ostringstream tooltip;
1636  tooltip << temp[image];
1637 
1638  const std::string& tt = adv["description"];
1639  if(!tt.empty()) {
1640  tooltip << tt << std::endl;
1641  }
1642 
1643  temp[image] = tooltip.str();
1644  }
1645 
1646  return(temp);
1647 }
1648 
1649 std::vector<std::pair<std::string, std::string>> unit::amla_icons() const
1650 {
1651  std::vector<std::pair<std::string, std::string>> temp;
1652  std::pair<std::string, std::string> icon; // <image,tooltip>
1653 
1654  for(const config& adv : get_modification_advances()) {
1655  icon.first = adv["icon"].str();
1656  icon.second = adv["description"].str();
1657 
1658  for(unsigned j = 0, j_count = modification_count("advancement", adv["id"]); j < j_count; ++j) {
1659  temp.push_back(icon);
1660  }
1661  }
1662 
1663  return(temp);
1664 }
1665 
1666 std::vector<config> unit::get_modification_advances() const
1667 {
1668  std::vector<config> res;
1669  for(const config& adv : modification_advancements()) {
1670  if(adv["strict_amla"].to_bool() && !advances_to_.empty()) {
1671  continue;
1672  }
1673 
1674  if(modification_count("advancement", adv["id"]) >= static_cast<unsigned>(adv["max_times"].to_int(1))) {
1675  continue;
1676  }
1677 
1678  std::vector<std::string> temp_require = utils::split(adv["require_amla"]);
1679  std::vector<std::string> temp_exclude = utils::split(adv["exclude_amla"]);
1680 
1681  if(temp_require.empty() && temp_exclude.empty()) {
1682  res.push_back(adv);
1683  continue;
1684  }
1685 
1686  std::sort(temp_require.begin(), temp_require.end());
1687  std::sort(temp_exclude.begin(), temp_exclude.end());
1688 
1689  std::vector<std::string> uniq_require, uniq_exclude;
1690 
1691  std::unique_copy(temp_require.begin(), temp_require.end(), std::back_inserter(uniq_require));
1692  std::unique_copy(temp_exclude.begin(), temp_exclude.end(), std::back_inserter(uniq_exclude));
1693 
1694  bool exclusion_found = false;
1695  for(const std::string& s : uniq_exclude) {
1696  int max_num = std::count(temp_exclude.begin(), temp_exclude.end(), s);
1697  int mod_num = modification_count("advancement", s);
1698  if(mod_num >= max_num) {
1699  exclusion_found = true;
1700  break;
1701  }
1702  }
1703 
1704  if(exclusion_found) {
1705  continue;
1706  }
1707 
1708  bool requirements_done = true;
1709  for(const std::string& s : uniq_require) {
1710  int required_num = std::count(temp_require.begin(), temp_require.end(), s);
1711  int mod_num = modification_count("advancement", s);
1712  if(required_num > mod_num) {
1713  requirements_done = false;
1714  break;
1715  }
1716  }
1717 
1718  if(requirements_done) {
1719  res.push_back(adv);
1720  }
1721  }
1722 
1723  return res;
1724 }
1725 
1726 void unit::set_advancements(std::vector<config> advancements)
1727 {
1728  this->advancements_.clear();
1729  for(config& advancement : advancements) {
1730  this->advancements_.push_back(new config());
1731  this->advancements_.back().swap(advancement);
1732  }
1733 }
1734 
1735 std::size_t unit::modification_count(const std::string& mod_type, const std::string& id) const
1736 {
1737  std::size_t res = 0;
1738  for(const config& item : modifications_.child_range(mod_type)) {
1739  if(item["id"] == id) {
1740  ++res;
1741  }
1742  }
1743 
1744  // For backwards compatibility, if asked for "advancement", also count "advance"
1745  if(mod_type == "advancement") {
1746  res += modification_count("advance", id);
1747  }
1748 
1749  return res;
1750 }
1751 
1752 const std::set<std::string> unit::builtin_effects {
1753  "alignment", "attack", "defense", "ellipse", "experience", "fearless",
1754  "halo", "healthy", "hitpoints", "image_mod", "jamming", "jamming_costs",
1755  "loyal", "max_attacks", "max_experience", "movement", "movement_costs",
1756  "new_ability", "new_advancement", "new_animation", "new_attack", "overlay", "profile",
1757  "recall_cost", "remove_ability", "remove_advancement", "remove_attacks", "resistance",
1758  "status", "type", "variation", "vision", "vision_costs", "zoc"
1759 };
1760 
1761 std::string unit::describe_builtin_effect(std::string apply_to, const config& effect)
1762 {
1763  if(apply_to == "attack") {
1764  std::vector<t_string> attack_names;
1765 
1766  std::string desc;
1767  for(attack_ptr a : attacks_) {
1768  bool affected = a->describe_modification(effect, &desc);
1769  if(affected && !desc.empty()) {
1770  attack_names.emplace_back(a->name(), "wesnoth-units");
1771  }
1772  }
1773  if(!attack_names.empty()) {
1774  utils::string_map symbols;
1775  symbols["attack_list"] = utils::format_conjunct_list("", attack_names);
1776  symbols["effect_description"] = desc;
1777  return VGETTEXT("$attack_list|: $effect_description", symbols);
1778  }
1779  } else if(apply_to == "hitpoints") {
1780  const std::string& increase_total = effect["increase_total"];
1781  if(!increase_total.empty()) {
1782  return VGETTEXT(
1783  "<span color=\"$color\">$number_or_percent</span> HP",
1784  {{"number_or_percent", utils::print_modifier(increase_total)}, {"color", increase_total[0] == '-' ? "red" : "green"}});
1785  }
1786  } else {
1787  const std::string& increase = effect["increase"];
1788  if(increase.empty()) {
1789  return "";
1790  }
1791  if(apply_to == "movement") {
1792  return VNGETTEXT(
1793  "<span color=\"$color\">$number_or_percent</span> move",
1794  "<span color=\"$color\">$number_or_percent</span> moves",
1795  std::stoi(increase),
1796  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1797  } else if(apply_to == "vision") {
1798  return VGETTEXT(
1799  "<span color=\"$color\">$number_or_percent</span> vision",
1800  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1801  } else if(apply_to == "jamming") {
1802  return VGETTEXT(
1803  "<span color=\"$color\">$number_or_percent</span> jamming",
1804  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1805  } else if(apply_to == "max_experience") {
1806  // Unlike others, decreasing experience is a *GOOD* thing
1807  return VGETTEXT(
1808  "<span color=\"$color\">$number_or_percent</span> XP to advance",
1809  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "green" : "red"}});
1810  } else if(apply_to == "max_attacks") {
1811  return VNGETTEXT(
1812  "<span color=\"$color\">$number_or_percent</span> attack per turn",
1813  "<span color=\"$color\">$number_or_percent</span> attacks per turn",
1814  std::stoi(increase),
1815  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1816  } else if(apply_to == "recall_cost") {
1817  // Unlike others, decreasing recall cost is a *GOOD* thing
1818  return VGETTEXT(
1819  "<span color=\"$color\">$number_or_percent</span> cost to recall",
1820  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "green" : "red"}});
1821  }
1822  }
1823  return "";
1824 }
1825 
1826 void unit::apply_builtin_effect(std::string apply_to, const config& effect)
1827 {
1828  appearance_changed_ = true;
1829  if(apply_to == "fearless") {
1830  is_fearless_ = effect["set"].to_bool(true);
1831  } else if(apply_to == "healthy") {
1832  is_healthy_ = effect["set"].to_bool(true);
1833  } else if(apply_to == "profile") {
1834  if(const config::attribute_value* v = effect.get("portrait")) {
1835  std::string portrait = (*v).str();
1836  adjust_profile(portrait);
1837  profile_ = portrait;
1838  }
1839 
1840  if(const config::attribute_value* v = effect.get("small_portrait")) {
1841  small_profile_ = (*v).str();
1842  }
1843 
1844  if(const config::attribute_value* v = effect.get("description")) {
1845  description_ = *v;
1846  }
1847  } else if(apply_to == "new_attack") {
1848  attacks_.emplace_back(new attack_type(effect));
1849  } else if(apply_to == "remove_attacks") {
1850  auto iter = std::remove_if(attacks_.begin(), attacks_.end(), [&effect](attack_ptr a) {
1851  return a->matches_filter(effect);
1852  });
1853 
1854  attacks_.erase(iter, attacks_.end());
1855  } else if(apply_to == "attack") {
1856  for(attack_ptr a : attacks_) {
1857  a->apply_modification(effect);
1858  }
1859  } else if(apply_to == "hitpoints") {
1860  LOG_UT << "applying hitpoint mod..." << hit_points_ << "/" << max_hit_points_ << std::endl;
1861  const std::string& increase_hp = effect["increase"];
1862  const std::string& increase_total = effect["increase_total"];
1863  const std::string& set_hp = effect["set"];
1864  const std::string& set_total = effect["set_total"];
1865 
1866  // If the hitpoints are allowed to end up greater than max hitpoints
1867  const bool violate_max = effect["violate_maximum"].to_bool();
1868 
1869  if(!set_hp.empty()) {
1870  if(set_hp.back() == '%') {
1871  hit_points_ = lexical_cast_default<int>(set_hp)*max_hit_points_/100;
1872  } else {
1873  hit_points_ = lexical_cast_default<int>(set_hp);
1874  }
1875  }
1876 
1877  if(!set_total.empty()) {
1878  if(set_total.back() == '%') {
1879  max_hit_points_ = lexical_cast_default<int>(set_total)*max_hit_points_/100;
1880  } else {
1881  max_hit_points_ = lexical_cast_default<int>(set_total);
1882  }
1883  }
1884 
1885  if(!increase_total.empty()) {
1886  // A percentage on the end means increase by that many percent
1888  }
1889 
1890  if(max_hit_points_ < 1)
1891  max_hit_points_ = 1;
1892 
1893  if(effect["heal_full"].to_bool()) {
1894  heal_fully();
1895  }
1896 
1897  if(!increase_hp.empty()) {
1899  }
1900 
1901  LOG_UT << "modded to " << hit_points_ << "/" << max_hit_points_ << std::endl;
1902  if(hit_points_ > max_hit_points_ && !violate_max) {
1903  LOG_UT << "resetting hp to max" << std::endl;
1905  }
1906 
1907  if(hit_points_ < 1) {
1908  hit_points_ = 1;
1909  }
1910  } else if(apply_to == "movement") {
1911  const std::string& increase = effect["increase"];
1912 
1913  if(!increase.empty()) {
1915  }
1916 
1917  max_movement_ = effect["set"].to_int(max_movement_);
1918 
1919  if(movement_ > max_movement_) {
1921  }
1922  } else if(apply_to == "vision") {
1923  const std::string& increase = effect["increase"];
1924 
1925  if(!increase.empty()) {
1926  const int current_vision = vision_ < 0 ? max_movement_ : vision_;
1927  vision_ = utils::apply_modifier(current_vision, increase, 1);
1928  }
1929 
1930  vision_ = effect["set"].to_int(vision_);
1931  } else if(apply_to == "jamming") {
1932  const std::string& increase = effect["increase"];
1933 
1934  if(!increase.empty()) {
1935  jamming_ = utils::apply_modifier(jamming_, increase, 1);
1936  }
1937 
1938  jamming_ = effect["set"].to_int(jamming_);
1939  } else if(apply_to == "experience") {
1940  const std::string& increase = effect["increase"];
1941  const std::string& set = effect["set"];
1942 
1943  if(!set.empty()) {
1944  if(set.back() == '%') {
1945  experience_ = lexical_cast_default<int>(set)*max_experience_/100;
1946  } else {
1947  experience_ = lexical_cast_default<int>(set);
1948  }
1949  }
1950 
1951  if(increase.empty() == false) {
1953  }
1954  } else if(apply_to == "max_experience") {
1955  const std::string& increase = effect["increase"];
1956  const std::string& set = effect["set"];
1957 
1958  if(set.empty() == false) {
1959  if(set.back() == '%') {
1960  max_experience_ = lexical_cast_default<int>(set)*max_experience_/100;
1961  } else {
1962  max_experience_ = lexical_cast_default<int>(set);
1963  }
1964  }
1965 
1966  if(increase.empty() == false) {
1968  }
1969  } else if(apply_to == upkeep_loyal::type()) {
1970  upkeep_ = upkeep_loyal();
1971  } else if(apply_to == "status") {
1972  const std::string& add = effect["add"];
1973  const std::string& remove = effect["remove"];
1974 
1975  for(const std::string& to_add : utils::split(add))
1976  {
1977  set_state(to_add, true);
1978  }
1979 
1980  for(const std::string& to_remove : utils::split(remove))
1981  {
1982  set_state(to_remove, false);
1983  }
1984  // Note: It would not be hard to define a new "applies_to=" that
1985  // combines the next five options (the movetype effects).
1986  } else if(apply_to == "movement_costs") {
1987  if(const config& ap = effect.child("movement_costs")) {
1988  movement_type_.get_movement().merge(ap, effect["replace"].to_bool());
1989  }
1990  } else if(apply_to == "vision_costs") {
1991  if(const config& ap = effect.child("vision_costs")) {
1992  movement_type_.get_vision().merge(ap, effect["replace"].to_bool());
1993  }
1994  } else if(apply_to == "jamming_costs") {
1995  if(const config& ap = effect.child("jamming_costs")) {
1996  movement_type_.get_jamming().merge(ap, effect["replace"].to_bool());
1997  }
1998  } else if(apply_to == "defense") {
1999  if(const config& ap = effect.child("defense")) {
2000  movement_type_.get_defense().merge(ap, effect["replace"].to_bool());
2001  }
2002  } else if(apply_to == "resistance") {
2003  if(const config& ap = effect.child("resistance")) {
2004  movement_type_.get_resistances().merge(ap, effect["replace"].to_bool());
2005  }
2006  } else if(apply_to == "zoc") {
2007  if(const config::attribute_value* v = effect.get("value")) {
2008  emit_zoc_ = v->to_bool();
2009  }
2010  } else if(apply_to == "new_ability") {
2011  if(const config& ab_effect = effect.child("abilities")) {
2012  config to_append;
2013  for(const config::any_child &ab : ab_effect.all_children_range()) {
2014  if(!has_ability_by_id(ab.cfg["id"])) {
2015  to_append.add_child(ab.key, ab.cfg);
2016  }
2017  }
2018  this->abilities_.append(to_append);
2019  }
2020  } else if(apply_to == "remove_ability") {
2021  if(const config& ab_effect = effect.child("abilities")) {
2022  for(const config::any_child &ab : ab_effect.all_children_range()) {
2023  remove_ability_by_id(ab.cfg["id"]);
2024  }
2025  }
2026  } else if(apply_to == "image_mod") {
2027  LOG_UT << "applying image_mod" << std::endl;
2028  std::string mod = effect["replace"];
2029  if(!mod.empty()){
2030  image_mods_ = mod;
2031  }
2032  LOG_UT << "applying image_mod" << std::endl;
2033  mod = effect["add"].str();
2034  if(!mod.empty()){
2035  if(!image_mods_.empty()) {
2036  image_mods_ += '~';
2037  }
2038 
2039  image_mods_ += mod;
2040  }
2041 
2043  LOG_UT << "applying image_mod" << std::endl;
2044  } else if(apply_to == "new_animation") {
2045  anim_comp_->apply_new_animation_effect(effect);
2046  } else if(apply_to == "ellipse") {
2047  set_image_ellipse(effect["ellipse"]);
2048  } else if(apply_to == "halo") {
2049  set_image_halo(effect["halo"]);
2050  } else if(apply_to == "overlay") {
2051  const std::string& add = effect["add"];
2052  const std::string& replace = effect["replace"];
2053 
2054  if(!add.empty()) {
2055  std::vector<std::string> temp_overlays = utils::parenthetical_split(add, ',');
2057  for(it=temp_overlays.begin();it<temp_overlays.end();++it) {
2058  overlays_.push_back(*it);
2059  }
2060  }
2061  else if(!replace.empty()) {
2062  overlays_ = utils::parenthetical_split(replace, ',');
2063  }
2064  } else if(apply_to == "new_advancement") {
2065  const std::string& types = effect["types"];
2066  const bool replace = effect["replace"].to_bool(false);
2067 
2068  if(!types.empty()) {
2069  if(replace) {
2071  } else {
2072  std::vector<std::string> temp_advances = utils::parenthetical_split(types, ',');
2073  std::copy(temp_advances.begin(), temp_advances.end(), std::back_inserter(advances_to_));
2074  }
2075  }
2076 
2077  if(effect.has_child("advancement")) {
2078  if(replace) {
2079  advancements_.clear();
2080  }
2081 
2082  config temp = effect;
2083  boost::copy(effect.child_range("advancement"), boost::make_function_output_iterator(ptr_vector_pushback(advancements_)));
2084  }
2085  } else if(apply_to == "remove_advancement") {
2086  const std::string& types = effect["types"];
2087  const std::string& amlas = effect["amlas"];
2088 
2089  std::vector<std::string> temp_advances = utils::parenthetical_split(types, ',');
2091  for(const std::string& unit : temp_advances) {
2092  iter = std::find(advances_to_.begin(), advances_to_.end(), unit);
2093  if(iter != advances_to_.end()) {
2094  advances_to_.erase(iter);
2095  }
2096  }
2097 
2098  temp_advances = utils::parenthetical_split(amlas, ',');
2099 
2100  for(int i = advancements_.size() - 1; i >= 0; i--) {
2101  if(std::find(temp_advances.begin(), temp_advances.end(), advancements_[i]["id"]) != temp_advances.end()) {
2102  advancements_.erase(advancements_.begin() + i);
2103  }
2104  }
2105  } else if(apply_to == "alignment") {
2106  unit_type::ALIGNMENT new_align;
2107  if(new_align.parse(effect["set"])) {
2108  alignment_ = new_align;
2109  }
2110  } else if(apply_to == "max_attacks") {
2111  const std::string& increase = effect["increase"];
2112 
2113  if(!increase.empty()) {
2115  }
2116  } else if(apply_to == "recall_cost") {
2117  const std::string& increase = effect["increase"];
2118  const std::string& set = effect["set"];
2119  const int recall_cost = recall_cost_ < 0 ? resources::gameboard->teams().at(side_).recall_cost() : recall_cost_;
2120 
2121  if(!set.empty()) {
2122  if(set.back() == '%') {
2123  recall_cost_ = lexical_cast_default<int>(set)*recall_cost/100;
2124  } else {
2125  recall_cost_ = lexical_cast_default<int>(set);
2126  }
2127  }
2128 
2129  if(!increase.empty()) {
2130  recall_cost_ = utils::apply_modifier(recall_cost, increase, 1);
2131  }
2132  } else if(effect["apply_to"] == "variation") {
2133  variation_ = effect["name"].str();
2134  const unit_type* base_type = unit_types.find(type().base_id());
2135  assert(base_type != nullptr);
2136  advance_to(*base_type);
2137  } else if(effect["apply_to"] == "type") {
2138  std::string prev_type = effect["prev_type"];
2139  if(prev_type.empty()) {
2140  prev_type = type().base_id();
2141  }
2142  const std::string& new_type_id = effect["name"];
2143  const unit_type* new_type = unit_types.find(new_type_id);
2144  if(new_type) {
2145  const bool heal_full = effect["heal_full"].to_bool(false);
2146  advance_to(*new_type);
2147  preferences::encountered_units().insert(new_type_id);
2148  if(heal_full) {
2149  heal_fully();
2150  }
2151  } else {
2152  WRN_UT << "unknown type= in [effect]apply_to=type, ignoring" << std::endl;
2153  }
2154  }
2155 }
2156 
2157 void unit::add_modification(const std::string& mod_type, const config& mod, bool no_add)
2158 {
2159  bool generate_description = mod["generate_description"].to_bool(true);
2160 
2161  if(no_add == false) {
2162  modifications_.add_child(mod_type, mod);
2163  }
2164 
2165  bool set_poisoned = false; // Tracks if the poisoned state was set after the type or variation was changed.
2166  config last_effect;
2167  std::vector<t_string> effects_description;
2168  for(const config& effect : mod.child_range("effect")) {
2169  // Apply SUF.
2170  if(const config& afilter = effect.child("filter")) {
2171  // @FIXME: during gamestate construction resources::filter_con is not available
2172  if(resources::filter_con && !unit_filter(vconfig(afilter)).matches(*this, loc_)) {
2173  continue;
2174  }
2175  }
2176  const std::string& apply_to = effect["apply_to"];
2177  int times = effect["times"].to_int(1);
2178  t_string description;
2179 
2180  if(effect["times"] == "per level") {
2181  times = level_;
2182  }
2183 
2184  if(times) {
2185  while (times > 0) {
2186  times --;
2187 
2188  bool was_poisoned = get_state(STATE_POISONED);
2189  if(apply_to == "variation" || apply_to == "type") {
2190  // Apply unit type/variation changes last to avoid double applying effects on advance.
2191  set_poisoned = false;
2192  last_effect = effect;
2193  continue;
2194  }
2195 
2196  std::string description_component;
2197  if(resources::lua_kernel) {
2198  description_component = resources::lua_kernel->apply_effect(apply_to, *this, effect, true);
2199  } else if(builtin_effects.count(apply_to)) {
2200  // Normally, the built-in effects are dispatched through Lua so that a user
2201  // can override them if desired. However, since they're built-in, we can still
2202  // apply them if the lua kernel is unavailable.
2203  apply_builtin_effect(apply_to, effect);
2204  description_component = describe_builtin_effect(apply_to, effect);
2205  }
2206  if(!times) {
2207  description += description_component;
2208  }
2209  if(!was_poisoned && get_state(STATE_POISONED)) {
2210  set_poisoned = true;
2211  } else if(was_poisoned && !get_state(STATE_POISONED)) {
2212  set_poisoned = false;
2213  }
2214  } // end while
2215  } else { // for times = per level & level = 0 we still need to rebuild the descriptions
2216  if(resources::lua_kernel) {
2217  description += resources::lua_kernel->apply_effect(apply_to, *this, effect, false);
2218  } else if(builtin_effects.count(apply_to)) {
2219  description += describe_builtin_effect(apply_to, effect);
2220  }
2221  }
2222 
2223  if(effect["times"] == "per level" && !times) {
2224  description = VGETTEXT("$effect_description per level", {{"effect_description", description}});
2225  }
2226 
2227  if(!description.empty()) {
2228  effects_description.push_back(description);
2229  }
2230  }
2231  // Apply variations -- only apply if we are adding this for the first time.
2232  if(!last_effect.empty() && no_add == false) {
2233  std::string description;
2234  if(resources::lua_kernel) {
2235  description = resources::lua_kernel->apply_effect(last_effect["apply_to"], *this, last_effect, true);
2236  } else if(builtin_effects.count(last_effect["apply_to"])) {
2237  apply_builtin_effect(last_effect["apply_to"], last_effect);
2238  description = describe_builtin_effect(last_effect["apply_to"], last_effect);
2239  }
2240  effects_description.push_back(description);
2241  if(set_poisoned)
2242  // An effect explicitly set the poisoned state, and this
2243  // should override the unit being immune to poison.
2244  set_state(STATE_POISONED, true);
2245  }
2246 
2247  t_string description;
2248 
2249  const t_string& mod_description = mod["description"];
2250  if(!mod_description.empty()) {
2251  description = mod_description;
2252  }
2253 
2254  // Punctuation should be translatable: not all languages use Latin punctuation.
2255  // (However, there maybe is a better way to do it)
2256  if(generate_description && !effects_description.empty()) {
2257  if(!mod_description.empty()) {
2258  description += "\n";
2259  }
2260 
2261  description += utils::format_conjunct_list("", effects_description);
2262  }
2263 
2264  // store trait info
2265  if(mod_type == "trait") {
2266  add_trait_description(mod, description);
2267  }
2268 
2269  //NOTE: if not a trait, description is currently not used
2270 }
2271 
2272 void unit::add_trait_description(const config& trait, const t_string& description)
2273 {
2274  const std::string& gender_string = gender_ == unit_race::FEMALE ? "female_name" : "male_name";
2275  const auto& gender_specific_name = trait[gender_string];
2276 
2277  const t_string name = gender_specific_name.empty() ? trait["name"] : gender_specific_name;
2278 
2279  if(!name.empty()) {
2280  trait_names_.push_back(name);
2281  trait_descriptions_.push_back(description);
2282  }
2283 }
2284 
2285 std::string unit::absolute_image() const
2286 {
2287  return type().icon().empty() ? type().image() : type().icon();
2288 }
2289 
2290 std::string unit::default_anim_image() const
2291 {
2292  return type().image().empty() ? type().icon() : type().image();
2293 }
2294 
2296 {
2297  log_scope("apply mods");
2298 
2299  variables_.clear_children("mods");
2300 
2301  for(const auto& mod : ModificationTypes) {
2302  if(mod == "advance" && modifications_.has_child(mod)) {
2303  deprecated_message("[advance]", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use [advancement] instead.");
2304  }
2305 
2306  for(const config& m : modifications_.child_range(mod)) {
2307  lg::scope_logger inner_scope_logging_object__(lg::general(), "add mod");
2308  add_modification(mod, m, true);
2309  }
2310  }
2311 
2312  // Apply the experience acceleration last
2314  max_experience_ = std::max<int>(1, (max_experience_ * exp_accel + 50)/100);
2315 }
2316 
2317 bool unit::invisible(const map_location& loc, bool see_all) const
2318 {
2319  if(loc != get_location()) {
2320  DBG_UT << "unit::invisible called: id = " << id() << " loc = " << loc << " get_loc = " << get_location() << std::endl;
2321  }
2322 
2323  // This is a quick condition to check, and it does not depend on the
2324  // location (so might as well bypass the location-based cache).
2325  if(get_state(STATE_UNCOVERED)) {
2326  return false;
2327  }
2328 
2329  // Fetch from cache
2330  /**
2331  * @todo FIXME: We use the cache only when using the default see_all=true
2332  * Maybe add a second cache if the see_all=false become more frequent.
2333  */
2334  if(see_all) {
2335  const auto itor = invisibility_cache_.find(loc);
2336  if(itor != invisibility_cache_.end()) {
2337  return itor->second;
2338  }
2339  }
2340 
2341  // Test hidden status
2342  static const std::string hides("hides");
2343  bool is_inv = get_ability_bool(hides, loc);
2344  if(is_inv){
2345  is_inv = (resources::gameboard ? !resources::gameboard->would_be_discovered(loc, side_,see_all) : true);
2346  }
2347 
2348  if(see_all) {
2349  // Add to caches
2350  if(invisibility_cache_.empty()) {
2351  units_with_cache.push_back(this);
2352  }
2353 
2354  invisibility_cache_[loc] = is_inv;
2355  }
2356 
2357  return is_inv;
2358 }
2359 
2360 bool unit::is_visible_to_team(const team& team, bool const see_all) const
2361 {
2362  const map_location& loc = get_location();
2363  if(!display::get_singleton()->get_map().on_board(loc)) {
2364  return false;
2365  }
2366 
2367  if(see_all) {
2368  return true;
2369  }
2370 
2371  if(team.is_enemy(side()) && invisible(loc)) {
2372  return false;
2373  }
2374 
2375  // allied planned moves are also visible under fog. (we assume that fake units on the map are always whiteboard markers)
2376  if(!team.is_enemy(side()) && underlying_id_.is_fake()) {
2377  return true;
2378  }
2379 
2380  // when the whiteboard planned unit map is applied, it uses moved the _real_ unit so
2381  // underlying_id_.is_fake() will be false and the check above will not apply.
2382  // TODO: improve this check so that is also works for allied planned units but without
2383  // breaking sp campaigns with allies under fog. We probably need an explicit flag
2384  // is_planned_ in unit that is set by the whiteboard.
2385  if(team.side() == side()) {
2386  return true;
2387  }
2388 
2389  if(team.fogged(loc)) {
2390  return false;
2391  }
2392 
2393  return true;
2394 }
2395 
2397 {
2398  if(underlying_id_.value == 0) {
2400  underlying_id_ = id_manager.next_id();
2401  } else {
2402  underlying_id_ = id_manager.next_fake_id();
2403  }
2404  }
2405 
2406  if(id_.empty() /*&& !underlying_id_.is_fake()*/) {
2407  std::stringstream ss;
2408  ss << (type_id().empty() ? "Unit" : type_id()) << "-" << underlying_id_.value;
2409  id_ = ss.str();
2410  }
2411 }
2412 
2413 unit& unit::mark_clone(bool is_temporary)
2414 {
2416  if(is_temporary) {
2417  underlying_id_ = ids.next_fake_id();
2418  } else {
2420  underlying_id_ = ids.next_id();
2421  }
2422  else {
2423  underlying_id_ = ids.next_fake_id();
2424  }
2425  std::string::size_type pos = id_.find_last_of('-');
2426  if(pos != std::string::npos && pos+1 < id_.size()
2427  && id_.find_first_not_of("0123456789", pos+1) == std::string::npos) {
2428  // this appears to be a duplicate of a generic unit, so give it a new id
2429  WRN_UT << "assigning new id to clone of generic unit " << id_ << std::endl;
2430  id_.clear();
2431  set_underlying_id(ids);
2432  }
2433  }
2434  return *this;
2435 }
2436 
2437 
2439  : u_(const_cast<unit&>(u))
2440  , moves_(u.movement_left(true))
2441 {
2442  if(operate) {
2444  }
2445 }
2446 
2448 {
2449  assert(resources::gameboard);
2450  try {
2451  if(!resources::gameboard->units().has_unit(&u_)) {
2452  /*
2453  * It might be valid that the unit is not in the unit map.
2454  * It might also mean a no longer valid unit will be assigned to.
2455  */
2456  DBG_UT << "The unit to be removed is not in the unit map." << std::endl;
2457  }
2458 
2460  } catch(...) {}
2461 }
2462 
2463 std::string unit::TC_image_mods() const
2464 {
2465  return formatter() << "~RC(" << flag_rgb() << ">" << team::get_side_color_id(side()) << ")";
2466 }
2467 
2468 std::string unit::image_mods() const
2469 {
2470  if(!image_mods_.empty()) {
2471  return formatter() << "~" << image_mods_ << TC_image_mods();
2472  }
2473 
2474  return TC_image_mods();
2475 }
2476 
2477 // Called by the Lua API after resetting an attack pointer.
2479 {
2480  auto iter = std::find(attacks_.begin(), attacks_.end(), atk);
2481  if(iter == attacks_.end()) {
2482  return false;
2483  }
2484  attacks_.erase(iter);
2485  return true;
2486 }
2487 
2489 {
2490  if(attacks_left_ == max_attacks_) {
2491  //TODO: add state_not_attacked
2492  }
2493 
2494  set_attacks(0);
2495 }
2496 
2498 {
2499  if(movement_left() == total_movement()) {
2500  set_state(STATE_NOT_MOVED,true);
2501  }
2502 
2503  set_movement(0, true);
2504 }
2505 
2506 void unit::set_hidden(bool state) const
2507 {
2508 // appearance_changed_ = true;
2509  hidden_ = state;
2510  if(!state) {
2511  return;
2512  }
2513 
2514  // We need to get rid of haloes immediately to avoid display glitches
2515  anim_comp_->clear_haloes();
2516 }
2517 
2518 void unit::set_image_halo(const std::string& halo)
2519 {
2520  appearance_changed_ = true;
2521  anim_comp_->clear_haloes();
2522  halo_.reset(new std::string(halo));
2523 }
2524 
2526 {
2527  if(upkeep.empty()) {
2528  return;
2529  }
2530 
2531  // TODO: create abetter way to check whether it is actually an int.
2532  int upkeep_int = upkeep.to_int(-99);
2533  if(upkeep_int != -99) {
2534  upkeep_ = upkeep_int;
2535  } else if(upkeep == upkeep_loyal::type() || upkeep == "free") {
2536  upkeep_ = upkeep_loyal();
2537  } else if(upkeep == upkeep_full::type()) {
2538  upkeep_ = upkeep_full();
2539  } else {
2540  WRN_UT << "Fund invalid upkeep=\"" << upkeep << "\" in a unit" << std::endl;
2541  upkeep_ = upkeep_full();
2542  }
2543 }
2544 
2546 {
2547  upkeep = boost::apply_visitor(upkeep_type_visitor(), upkeep_);
2548 }
2549 
2550 // Filters unimportant stats from the unit config and returns a checksum of
2551 // the remaining config.
2552 std::string get_checksum(const unit& u)
2553 {
2554  config unit_config;
2555  config wcfg;
2556  u.write(unit_config);
2557 
2558  const std::array<std::string, 22> main_keys {{
2559  "advances_to",
2560  "alignment",
2561  "cost",
2562  "experience",
2563  "gender",
2564  "hitpoints",
2565  "ignore_race_traits",
2566  "ignore_global_traits",
2567  "level",
2568  "recall_cost",
2569  "max_attacks",
2570  "max_experience",
2571  "max_hitpoints",
2572  "max_moves",
2573  "movement",
2574  "movement_type",
2575  "race",
2576  "random_traits",
2577  "resting",
2578  "undead_variation",
2579  "upkeep",
2580  "zoc"
2581  }};
2582 
2583  for(const std::string& main_key : main_keys) {
2584  wcfg[main_key] = unit_config[main_key];
2585  }
2586 
2587  const std::array<std::string, 5> attack_keys {{
2588  "name",
2589  "type",
2590  "range",
2591  "damage",
2592  "number"
2593  }};
2594 
2595  for(const config& att : unit_config.child_range("attack")) {
2596  config& child = wcfg.add_child("attack");
2597 
2598  for(const std::string& attack_key : attack_keys) {
2599  child[attack_key] = att[attack_key];
2600  }
2601 
2602  for(const config& spec : att.child_range("specials")) {
2603  config& child_spec = child.add_child("specials", spec);
2604 
2605  child_spec.recursive_clear_value("description");
2606  }
2607  }
2608 
2609  for(const config& abi : unit_config.child_range("abilities")) {
2610  config& child = wcfg.add_child("abilities", abi);
2611 
2612  child.recursive_clear_value("description");
2613  child.recursive_clear_value("description_inactive");
2614  child.recursive_clear_value("name");
2615  child.recursive_clear_value("name_inactive");
2616  }
2617 
2618  for(const config& trait : unit_config.child_range("trait")) {
2619  config& child = wcfg.add_child("trait", trait);
2620 
2621  child.recursive_clear_value("description");
2622  child.recursive_clear_value("male_name");
2623  child.recursive_clear_value("female_name");
2624  child.recursive_clear_value("name");
2625  }
2626 
2627  const std::array<std::string, 6> child_keys {{
2628  "advance_from",
2629  "defense",
2630  "movement_costs",
2631  "vision_costs",
2632  "jamming_costs",
2633  "resistance"
2634  }};
2635 
2636  for(const std::string& child_key : child_keys) {
2637  for(const config& c : unit_config.child_range(child_key)) {
2638  wcfg.add_child(child_key, c);
2639  }
2640  }
2641 
2642  DBG_UT << wcfg;
2643 
2644  return wcfg.hash();
2645 }
2646 
2647 void swap(unit& lhs, unit& rhs)
2648 {
2649  lhs.swap(rhs);
2650 }
void set_wml_y(int v)
Definition: location.hpp:161
unit_id next_fake_id()
Definition: id.cpp:34
int defense_modifier(const t_translation::terrain_code &terrain) const
Returns the defensive value of the indicated terrain.
Definition: movetype.hpp:207
bool empty() const
Tests for an attribute that either was never set or was set to "".
const std::string & base_id() const
The id of the original type from which this (variation) descended.
Definition: types.hpp:143
const unit_type * type_
Never nullptr.
Definition: unit.hpp:1610
attack_list attacks_
Definition: unit.hpp:1678
void set_movement(int moves, bool unit_action=false)
Set this unit&#39;s remaining movement to moves.
Definition: unit.cpp:1157
t_string type_name_
The displayed name of this unit type.
Definition: unit.hpp:1613
std::string apply_effect(const std::string &name, unit &u, const config &cfg, bool need_apply)
static DIRECTION parse_direction(const std::string &str)
Definition: location.cpp:64
bool empty() const
Definition: unit.hpp:78
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:423
std::string format_conjunct_list(const t_string &empty, const std::vector< t_string > &elems)
Format a conjunctive list.
V::result_t apply_visitor(typename V::param_t state, T &&... args)
Helper function to apply the result of a specified visitor to a variable_info object.
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:99
std::vector< std::string > recruit_list_
Definition: unit.hpp:1634
static int get_acceleration()
Definition: types.cpp:524
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:874
static state_t get_known_boolean_state_id(const std::string &state)
Convert a string status effect ID to a built-in status effect ID.
Definition: unit.cpp:1318
resistances & get_resistances()
Definition: movetype.hpp:183
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:1265
virtual const std::vector< team > & teams() const override
Definition: game_board.hpp:92
ptr_vector_pushback(boost::ptr_vector< config > &vec)
Definition: unit.cpp:286
config modifications_
Definition: unit.hpp:1704
int recall_cost_
Definition: unit.hpp:1632
utils::string_map modification_descriptions_
Definition: unit.hpp:1694
vconfig child(const std::string &key) const
Returns a child of *this whose key is key.
Definition: variable.cpp:252
std::map< std::string, t_string > string_map
void apply_modifications()
Re-apply all saved modifications.
Definition: unit.cpp:2295
void clear_children(T... keys)
Definition: config.hpp:477
void recursive_clear_value(config_key_type key)
Definition: config.cpp:605
void parse_upkeep(const config::attribute_value &upkeep)
Definition: unit.cpp:2525
The unit is a guardian - it won&#39;t move unless a target is sighted.
Definition: unit.hpp:747
This class represents a single unit of a specific type.
Definition: unit.hpp:99
std::string big_profile() const
An optional profile image displays when this unit is &#39;speaking&#39; via [message].
Definition: unit.cpp:1004
Interfaces for manipulating version numbers of engine, add-ons, etc.
void intrusive_ptr_release(const unit *u)
Definition: unit.cpp:230
bool generate_name() const
Definition: types.hpp:168
void append(const config &cfg)
Append data from another config object to this one.
Definition: config.cpp:291
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
void advance_to(const unit_type &t, bool use_traits=false)
Advances this unit to another type.
Definition: unit.cpp:888
void new_turn()
Refresh unit for the beginning of a turn.
Definition: unit.cpp:1218
The unit is uncovered - it was hiding but has been spotted.
Definition: unit.hpp:744
std::string image_mods_
Definition: unit.hpp:1638
void set_usage(const std::string &usage)
Sets this unit&#39;s usage.
Definition: unit.hpp:575
std::vector< std::string > advances_to_
Definition: unit.hpp:1607
t_string name_
Definition: unit.hpp:1619
unit_id next_id()
returns id for unit that is created
Definition: id.cpp:27
iterator erase(const iterator &erase_it)
Definition: unit.hpp:84
const std::string & id() const
Definition: race.hpp:34
config::const_child_itors events() const
Definition: types.hpp:232
Variant for storing WML attributes.
std::vector< t_string > trait_names_
Definition: unit.hpp:1686
void write_upkeep(config::attribute_value &upkeep) const
Definition: unit.cpp:2545
bool get_state(const std::string &state) const
Check if the unit is affected by a status effect.
Definition: unit.cpp:1290
int vision_
Definition: unit.hpp:1650
const std::string & big_profile() const
Definition: types.hpp:165
unit_race::GENDER gender() const
The gender of this unit.
Definition: unit.hpp:381
void check_types(const std::vector< std::string > &types) const
Definition: types.cpp:1290
const std::vector< std::string > & advances_to() const
A vector of unit_type ids that this unit_type can advance to.
Definition: types.hpp:113
static l_noret error(LoadState *S, const char *why)
Definition: lundump.cpp:39
static id_manager & global_instance()
Definition: id.hpp:60
New lexcical_cast header.
#define a
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:414
config events_
Definition: unit.hpp:1670
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:416
const std::string & flag_rgb() const
Definition: types.cpp:733
unsigned child_count(config_key_type key) const
Definition: config.cpp:394
unit_type::ALIGNMENT alignment_
Definition: unit.hpp:1635
bool is_fearless_
Definition: unit.hpp:1692
void intrusive_ptr_add_ref(const unit *u)
Intrusive Pointer interface.
Definition: unit.cpp:215
map_location::DIRECTION facing_
Definition: unit.hpp:1683
child_itors child_range(config_key_type key)
Definition: config.cpp:366
bool loyal() const
Gets whether this unit is loyal - ie, it costs no upkeep.
Definition: unit.cpp:1536
std::string flag_rgb_
Definition: unit.hpp:1637
config & variables()
Gets any user-defined variables this unit &#39;owns&#39;.
Definition: unit.hpp:586
void set_image_ellipse(const std::string &ellipse)
Set the unit&#39;s ellipse image.
Definition: unit.hpp:1388
int jamming_
Definition: unit.hpp:1651
int unit_value_
Definition: unit.hpp:1689
A status effect not known to the engine.
Definition: unit.hpp:748
attribute_map::value_type attribute
Definition: config.hpp:226
const std::vector< std::string > & advances_to() const
Gets the possible types this unit can advance to on level-up.
Definition: unit.hpp:165
bool generate_name_
Definition: unit.hpp:1716
const attribute_value * get(config_key_type key) const
Returns a pointer to the attribute with the given key or nullptr if it does not exist.
Definition: config.cpp:695
std::string unit_rgb
bool hold_position_
Definition: unit.hpp:1655
int wml_x() const
Definition: location.hpp:157
The unit is poisoned - it loses health each turn.
Definition: unit.hpp:742
A terrain string which is converted to a terrain is a string with 1 or 2 layers the layers are separa...
Definition: translation.hpp:50
int experience_needed(bool with_acceleration=true) const
Definition: types.cpp:529
unit_type_data unit_types
Definition: types.cpp:1442
void set_wml_x(int v)
Definition: location.hpp:160
The unit is petrified - it cannot move or be attacked.
Definition: unit.hpp:743
config variables_
Definition: unit.hpp:1669
const config & get_cfg() const
Definition: types.hpp:269
void merge(const config &new_data, bool overwrite)
Merges the given config over the existing costs.
Definition: movetype.cpp:659
int resistance_against(const attack_type &attack) const
Returns the resistance against the indicated attack.
Definition: movetype.hpp:211
std::string absolute_image() const
The name of the file to game_display (used in menus).
Definition: unit.cpp:2285
#define VNGETTEXT(msgid, msgid_plural, count,...)
bool matches(const unit &u, const map_location &loc) const
Determine if *this matches filter at a specified location.
Definition: filter.hpp:114
const std::string & type_id() const
The id of this unit&#39;s type.
Definition: unit.hpp:288
void clear()
Definition: config.cpp:816
void remove_attacks_ai()
Set the unit to have no attacks left for this turn.
Definition: unit.cpp:2488
void merge(const config &new_cfg, bool overwrite=true)
Merges the given config over the existing data.
Definition: movetype.cpp:749
void write(config &cfg) const
Writes the movement type data to the provided config.
Definition: movetype.cpp:787
bool is_healthy_
Definition: unit.hpp:1692
-file sdl_utils.hpp
void set_facing(map_location::DIRECTION dir) const
The this unit&#39;s facing.
Definition: unit.cpp:1517
void set_interrupted_move(const map_location &interrupted_move)
Set the target location of the unit&#39;s interrupted move.
Definition: unit.hpp:1241
int max_hit_points_
Definition: unit.hpp:1626
std::vector< std::string > split(const std::string &val, const char c, const int flags)
Splits a (comma-)separated string into a vector of pieces.
static void add_color_info(const config &v, bool build_defaults)
void operator()(const config &cfg)
Definition: unit.cpp:288
const_attr_itors attribute_range() const
Definition: config.cpp:762
std::string small_profile_
Definition: unit.hpp:1721
A single unit type that the player may recruit.
Definition: types.hpp:42
game_data * gamedata
Definition: resources.cpp:22
static std::map< std::string, state_t > known_boolean_state_names_
Definition: unit.hpp:1667
map_location goto_
Definition: unit.hpp:1690
bool filter_base_matches(const config &cfg, int def)
Definition: abilities.cpp:1103
std::vector< unit_ability >::iterator iterator
Definition: unit.hpp:69
terrain_costs & get_jamming()
Definition: movetype.hpp:181
state_t
Built-in status effects known to the engine.
Definition: unit.hpp:740
map_location loc_
std::unique_ptr< unit_formula_manager > formula_man_
Definition: unit.hpp:1646
const unit_type & type() const
This unit&#39;s type, accounting for gender and variation.
Definition: unit.hpp:277
color_t hp_color() const
Color for this unit&#39;s current hitpoints.
Definition: unit.cpp:1074
unsigned int experience_to_advance() const
The number of experience points this unit needs to level up, or 0 if current XP > max XP...
Definition: unit.hpp:444
std::vector< std::string > get_traits_list() const
Gets a list of the traits this unit currently has.
Definition: unit.cpp:868
void heal(int amount)
Heal the unit The number of hitpoints to gain.
Definition: unit.cpp:1257
void add_modification(const std::string &type, const config &modification, bool no_add=false)
Add a new modification to the unit.
Definition: unit.cpp:2157
int defense_modifier(const t_translation::terrain_code &terrain) const
The unit&#39;s defense on a given terrain.
Definition: unit.cpp:1541
static void clear_status_caches()
Clear this unit status cache for all units.
Definition: unit.cpp:685
void set_advances_to(const std::vector< std::string > &advances_to)
Sets this unit&#39;s advancement options.
Definition: unit.cpp:1151
const_all_children_iterator ordered_end() const
Definition: config.cpp:864
child_list get_children(const std::string &key) const
Definition: variable.cpp:190
std::string role_
Definition: unit.hpp:1677
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:44
#define LOG_UT
Definition: unit.cpp:79
A small explanation about what&#39;s going on here: Each action has access to two game_info objects First...
Definition: actions.cpp:58
static const std::string & leader_crown()
The path to the leader crown overlay.
Definition: unit.cpp:1026
const config & get_cfg_for_units() const
Returns a trimmed config suitable for use with units.
Definition: types.hpp:271
std::size_t size(const std::string &str)
Length in characters of a UTF-8 string.
Definition: unicode.cpp:86
const std::vector< unit_race::GENDER > & genders() const
The returned vector will not be empty, provided this has been built to the HELP_INDEXED status...
Definition: types.hpp:239
const std::string & id() const
Gets this unit&#39;s id.
Definition: unit.hpp:305
void generate_traits(bool must_have_only=false)
Applies mandatory traits (e.g.
Definition: unit.cpp:811
void swap(unit &)
Swap, for copy and swap idiom.
Definition: unit.cpp:738
std::string deprecated_message(const std::string &elem_name, DEP_LEVEL level, const version_info &version, const std::string &detail)
Definition: deprecation.cpp:29
int cost() const
Definition: types.hpp:158
void set_state(const std::string &state, bool value)
Set whether the unit is affected by a status effect.
Definition: unit.cpp:1338
int vision() const
Definition: types.hpp:153
static const unit_race null_race
Dummy race used when a race is not yet known.
Definition: race.hpp:66
unit_movement_resetter(const unit_movement_resetter &)=delete
void set_underlying_id(n_unit::id_manager &id_manager)
Sets the internal ID.
Definition: unit.cpp:2396
const movetype & movement_type() const
Definition: types.hpp:174
The unit is slowed - it moves slower and does less damage.
Definition: unit.hpp:741
void set_recruits(const std::vector< std::string > &recruits)
Sets the recruit list.
Definition: unit.cpp:1127
std::ostringstream wrapper.
Definition: formatter.hpp:38
const t_string & type_name() const
The name of the unit in the current language setting.
Definition: types.hpp:136
std::string profile_
Definition: unit.hpp:1720
int max_movement_
Definition: unit.hpp:1649
void new_scenario()
Refresh unit for the beginning of a new scenario.
Definition: unit.cpp:1242
int wml_y() const
Definition: location.hpp:158
filter_context * filter_con
Definition: resources.cpp:23
const std::vector< std::string > advances_to_translated() const
Gets the names of the possible types this unit can advance to on level-up.
Definition: unit.cpp:1136
const std::string & usage() const
Definition: types.hpp:161
color_t xp_color() const
Color for this unit&#39;s XP.
Definition: unit.cpp:1084
terrain_defense & get_defense()
Definition: movetype.hpp:182
terrain_costs & get_vision()
Definition: movetype.hpp:180
game_board * gameboard
Definition: resources.cpp:20
std::string ellipse() const
Definition: types.hpp:167
void add_trait_description(const config &trait, const t_string &description)
Register a trait&#39;s name and its description for the UI&#39;s use.
Definition: unit.cpp:2272
#define WRN_UT
Definition: unit.cpp:80
bool appearance_changed_
Definition: unit.hpp:1724
const t_string & name() const
Gets this unit&#39;s translatable display name.
Definition: unit.hpp:328
unit_race::GENDER string_gender(const std::string &str, unit_race::GENDER def)
Definition: race.cpp:149
int kill_experience
Definition: game_config.cpp:57
uint8_t r
Red value.
Definition: color.hpp:177
bool is_enemy(int n) const
Definition: team.hpp:243
int max_experience_
Definition: unit.hpp:1628
std::size_t value
Definition: id.hpp:26
const std::string & id() const
The id for this unit_type.
Definition: types.hpp:139
void set_hidden(bool state) const
Sets whether the unit is hidden on the map.
Definition: unit.cpp:2506
map_display and display: classes which take care of displaying the map and game-data on the screen...
int upkeep() const
Gets the amount of gold this unit costs a side per turn.
Definition: unit.cpp:1526
std::string default_anim_image() const
The default image to use for animation frames with no defined image.
Definition: unit.cpp:2290
boost::iterator_range< const_attribute_iterator > const_attr_itors
Definition: config.hpp:286
std::string small_profile() const
An optional profile image to display in Help.
Definition: unit.cpp:1013
The unit has not moved.
Definition: unit.hpp:745
void set_advancements(std::vector< config > advancements)
Sets the raw modification advancement option data.
Definition: unit.cpp:1726
bool mod_duration_match(const std::string &mod_dur, const std::string &goal_dur)
Determines if mod_dur "matches" goal_dur.
Definition: unit.cpp:1173
unit_race::GENDER gender_
Definition: unit.hpp:1644
int hit_points_
Definition: unit.hpp:1625
void merge(const config &new_data, bool overwrite)
Merges the given config over the existing costs.
Definition: movetype.hpp:136
std::unique_ptr< std::string > ellipse_
Definition: unit.hpp:1713
game_events::manager * game_events
Definition: resources.cpp:24
bool random_traits_
Definition: unit.hpp:1715
terrain_costs & get_movement()
Definition: movetype.hpp:179
all_children_iterator erase(const all_children_iterator &i)
Definition: config.cpp:642
void expire_modifications(const std::string &duration)
Clears those modifications whose duration has expired.
Definition: unit.cpp:1183
std::size_t modification_count(const std::string &type, const std::string &id) const
Count modifications of a particular type.
Definition: unit.cpp:1735
log_domain & general()
Definition: log.cpp:104
const std::string & gender_string(unit_race::GENDER gender)
Definition: race.cpp:138
std::string flag_rgb
static std::string get_side_color_id(unsigned side)
Definition: team.cpp:962
double xp_bar_scaling() const
Definition: types.hpp:149
unit & mark_clone(bool is_temporary)
Mark this unit as clone so it can be inserted to unit_map.
Definition: unit.cpp:2413
bool is_fake() const
Definition: id.hpp:28
config abilities_
Definition: unit.hpp:1705
std::vector< std::string > overlays_
Definition: unit.hpp:1675
Encapsulates the map of the game.
Definition: location.hpp:42
boost::iterator_range< const_child_iterator > const_child_itors
Definition: config.hpp:210
bool hidden_
Definition: unit.hpp:1701
bool invisible(const map_location &loc, bool see_all=true) const
Definition: unit.cpp:2317
const advancements_list & modification_advancements() const
The raw, unparsed data for modification advancements.
Definition: unit.hpp:245
const std::string & undead_variation() const
Info on the type of unit that the unit reanimates as.
Definition: types.hpp:131
#define DBG_UT
Definition: unit.cpp:78
movetype movement_type_
Definition: unit.hpp:1653
const std::string log_id() const
A variant on id() that is more descriptive, for use with message logging.
Definition: types.hpp:141
bool get_ability_bool(const std::string &tag_name, const map_location &loc) const
Checks whether this unit currently possesses or is affected by a given ability.
Definition: abilities.cpp:140
config filter_recall_
Definition: unit.hpp:1671
const unit_race * find_race(const std::string &) const
Definition: types.cpp:1410
void remove_ability_by_id(const std::string &ability)
Removes a unit&#39;s abilities with a specific ID.
Definition: unit.cpp:1372
bool has_zoc() const
Definition: types.hpp:218
void set_image_halo(const std::string &halo)
Set the unit&#39;s halo image.
Definition: unit.cpp:2518
void generate_name()
Generates a random race-appropriate name if one has not already been provided.
Definition: unit.cpp:802
int max_attacks_
Definition: unit.hpp:1660
void swap(unit &lhs, unit &rhs)
Implement non-member swap function for std::swap (calls unit::swap).
Definition: unit.cpp:2647
std::size_t i
Definition: function.cpp:933
int recall_cost() const
Definition: types.hpp:151
int max_hitpoints() const
The max number of hitpoints this unit can have.
Definition: unit.hpp:420
Visitor helper class to fetch the appropriate upkeep value.
Definition: unit.hpp:1006
std::string get_checksum(const unit &u)
Gets a checksum for a unit.
Definition: unit.cpp:2552
double hp_bar_scaling_
Definition: unit.hpp:1702
static map_location::DIRECTION s
map_location interrupted_move_
Definition: unit.hpp:1690
const config & abilities_cfg() const
Definition: types.hpp:226
bool can_recruit() const
Whether this unit can recruit other units - ie, are they a leader unit.
Definition: unit.hpp:502
iterator begin()
Definition: unit.hpp:72
bool canrecruit_
Definition: unit.hpp:1633
std::map< std::string, std::string > advancement_icons() const
Gets and image path and and associated description for each advancement option.
Definition: unit.cpp:1609
int experience_
Definition: unit.hpp:1627
std::unique_ptr< std::string > usage_
Definition: unit.hpp:1711
#define log_scope(description)
Definition: log.hpp:186
std::string halo() const
Definition: types.hpp:166
n_unit::unit_id underlying_id_
Definition: unit.hpp:1620
double xp_bar_scaling_
Definition: unit.hpp:1702
int get_composite_value() const
Definition: abilities.hpp:49
DIRECTION
Valid directions which can be moved in our hexagonal world.
Definition: location.hpp:44
const std::string & icon() const
Definition: types.hpp:163
void validate_side(int side)
Definition: team.cpp:750
int level() const
Definition: types.hpp:150
t_string description_
Definition: unit.hpp:1709
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:180
std::set< std::string > & encountered_units()
Definition: game.cpp:927
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
int attacks_left_
Definition: unit.hpp:1659
void heal_fully()
Fully heal the unit, restoring it to max hitpoints.
Definition: unit.hpp:712
static int sort(lua_State *L)
Definition: ltablib.cpp:411
#define VGETTEXT(msgid,...)
Handy wrappers around interpolate_variables_into_string and gettext.
const std::string & small_profile() const
Definition: types.hpp:164
int hitpoints() const
Definition: types.hpp:147
The unit cannot be healed.
Definition: unit.hpp:746
int jamming() const
Definition: types.hpp:156
std::unique_ptr< std::string > halo_
Definition: unit.hpp:1712
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
int movement() const
Definition: types.hpp:152
std::shared_ptr< attack_type > attack_ptr
Definition: ptr.hpp:36
config & add_child(config_key_type key)
Definition: config.cpp:479
bool is_visible_to_team(const team &team, bool const see_all=true) const
Definition: unit.cpp:2360
advancements_list advancements_
Definition: unit.hpp:1707
Handling of system events.
Definition: manager.hpp:41
const std::vector< std::string > & recruits() const
The type IDs of the other units this unit may recruit, if possible.
Definition: unit.hpp:514
const std::string & flag_rgb() const
Get the source color palette to use when recoloring the unit&#39;s image.
Definition: unit.cpp:1031
long ref_count_
Definition: unit.hpp:1602
const_all_children_iterator ordered_begin() const
Definition: config.cpp:854
std::unique_ptr< unit_animation_component > anim_comp_
Definition: unit.hpp:1699
static std::string type()
Definition: unit.hpp:1002
config::const_child_itors possible_traits() const
Definition: types.hpp:223
const std::string & image() const
Definition: types.hpp:162
static const unit_type & get_unit_type(const std::string &type_id)
Converts a string ID to a unit_type.
Definition: unit.cpp:245
Definition: display.hpp:44
static unit_race::GENDER generate_gender(const unit_type &type, bool random_gender)
Definition: unit.cpp:257
bool empty() const
Definition: tstring.hpp:182
void init(const config &cfg, bool use_traits=false, const vconfig *vcfg=nullptr)
Definition: unit.cpp:451
unsigned int num_traits() const
Definition: types.hpp:133
int movement_
Definition: unit.hpp:1648
static const std::set< std::string > builtin_effects
Definition: unit.hpp:1334
n_unit::id_manager & unit_id_manager()
Definition: game_board.hpp:86
double t
Definition: astarsearch.cpp:63
const unit_type & get_variation(const std::string &id) const
Definition: types.cpp:467
upkeep_t upkeep_
Definition: unit.hpp:1718
int apply_modifier(const int number, const std::string &amount, const int minimum)
bool unrenamable_
Definition: unit.hpp:1640
int level_
Definition: unit.hpp:1630
std::vector< config > get_modification_advances() const
Gets any non-typed advanced options set by modifications.
Definition: unit.cpp:1666
int max_attacks() const
Definition: types.hpp:157
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1174
std::bitset< num_bool_states > known_boolean_states_
Definition: unit.hpp:1666
A variable-expanding proxy for the config class.
Definition: variable.hpp:42
const unit_race * race() const
Never returns nullptr, but may point to the null race.
Definition: types.hpp:265
this module manages the cache of images.
void adjust_profile(std::string &profile)
Definition: types.cpp:1444
const config & get_config() const
Definition: variable.hpp:75
Standard logging facilities (interface).
bool can_advance() const
Checks whether this unit has any options to advance to.
Definition: unit.hpp:193
const unit_race * race_
Never nullptr, but may point to the null race.
Definition: unit.hpp:1616
void apply_builtin_effect(std::string type, const config &effect)
Apply a builtin effect to the unit.
Definition: unit.cpp:1826
std::string variation_
Definition: unit.hpp:1623
t_string unit_description() const
A detailed description of this unit.
Definition: unit.hpp:375
const unit_type & get_gender_unit_type(std::string gender) const
Returns a gendered variant of this unit_type.
Definition: types.cpp:446
static void check_id(std::string &id)
Validate the id argument.
Definition: types.cpp:1416
bool emit_zoc_
Definition: unit.hpp:1673
game_lua_kernel * lua_kernel
Definition: resources.cpp:25
std::string describe_builtin_effect(std::string type, const config &effect)
Construct a string describing a built-in effect.
Definition: unit.cpp:1761
void write(config &cfg) const
Serializes the current unit metadata values.
Definition: unit.cpp:1384
std::map< map_location, bool > invisibility_cache_
Hold the visibility status cache for a unit, when not uncovered.
Definition: unit.hpp:1733
double hp_bar_scaling() const
Definition: types.hpp:148
int total_movement() const
The maximum moves this unit has.
Definition: unit.hpp:1090
const map_location goto_
Definition: move.cpp:306
bool fogged(const map_location &loc) const
Definition: team.cpp:653
std::string id_
Definition: unit.hpp:1618
#define e
int side() const
The side this unit belongs to.
Definition: unit.hpp:265
std::vector< t_string > trait_descriptions_
Definition: unit.hpp:1687
void end_turn()
Refresh unit for the end of a turn.
Definition: unit.cpp:1228
boost::ptr_vector< config > * vec_
Definition: unit.cpp:294
static color_t hp_color_impl(int hitpoints, int max_hitpoints)
Definition: unit.cpp:1036
bool resting_
Definition: unit.hpp:1657
const config & child_or_empty(config_key_type key) const
Returns the first child with the given key, or an empty config if there is none.
Definition: config.cpp:456
const_attack_itors attacks() const
Definition: types.cpp:495
int resistance_against(const std::string &damage_name, bool attacker, const map_location &loc, const_attack_ptr weapon=nullptr, const_attack_ptr opp_weapon=nullptr) const
The unit&#39;s resistance against a given damage type.
Definition: unit.cpp:1584
std::vector< vconfig > child_list
Definition: variable.hpp:78
std::vector< std::pair< std::string, std::string > > amla_icons() const
Gets the image and description data for modification advancements.
Definition: unit.cpp:1649
int side() const
Definition: team.hpp:188
t_string unit_description() const
Definition: types.cpp:477
#define ERR_UT
Definition: unit.cpp:81
Visitor helper struct to fetch the upkeep type flag if applicable, or the the value otherwise...
Definition: unit.hpp:1033
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
bool null() const
Definition: variable.hpp:73
map_location loc_
Definition: unit.hpp:1605
mock_char c
bool resistance_filter_matches(const config &cfg, bool attacker, const std::string &damage_name, int res) const
Definition: unit.cpp:1556
std::shared_ptr< const attack_type > const_attack_ptr
Definition: ptr.hpp:37
std::string TC_image_mods() const
Constructs a recolor (RC) IPF string for this unit&#39;s team color.
Definition: unit.cpp:2463
void remove_movement_ai()
Sets the unit to have no moves left for this turn.
Definition: unit.cpp:2497
const std::set< std::string > get_states() const
Get the status effects currently affecting the unit.
Definition: unit.cpp:1273
virtual ~unit()
Definition: unit.cpp:719
std::string print_modifier(const std::string &mod)
Add a "+" or replace the "-" par Unicode minus.
int recall_cost() const
How much gold it costs to recall this unit.
Definition: unit.hpp:529
unit()
Definition: unit.cpp:377
static std::string write_direction(DIRECTION dir)
Definition: location.cpp:139
void remove_child(config_key_type key, unsigned index)
Definition: config.cpp:647
bool would_be_discovered(const map_location &loc, int side_num, bool see_all=true)
Given a location and a side number, indicates whether an invisible unit of that side at that location...
static rng & default_instance()
Definition: random.cpp:73
static bool is_synced()
std::string hash() const
Definition: config.cpp:1275
void add_events(const config::const_child_itors &cfgs, const std::string &type=std::string())
Definition: manager.cpp:115
int side_
Definition: unit.hpp:1642
static lg::log_domain log_unit("unit")
std::string::const_iterator iterator
Definition: tokenizer.hpp:24
int movement_left() const
Gets how far a unit can move, considering the incapacitated flag.
Definition: unit.hpp:1100
std::size_t underlying_id() const
This unit&#39;s unique internal ID.
Definition: unit.hpp:317
void merge(const config &new_values, bool overwrite)
Merges the given config over the existing values.
Definition: movetype.cpp:506
bool empty() const
Definition: config.cpp:837
std::string image_mods() const
Gets an IPF string containing all IPF image mods.
Definition: unit.cpp:2468
bool has_ability_by_id(const std::string &ability) const
Check if the unit has an ability of a specific ID.
Definition: unit.cpp:1361
iterator end()
Definition: unit.hpp:74
config::const_child_itors advancements() const
Definition: types.hpp:229
std::string generate_name(GENDER gender) const
Definition: race.cpp:108
bool end_turn_
Definition: unit.hpp:1656
std::pair< int, map_location > highest(const std::string &key, int def=0) const
Definition: unit.hpp:56
std::set< std::string > states_
Definition: unit.hpp:1662
const std::string & default_variation() const
Definition: types.hpp:159
std::string undead_variation_
Definition: unit.hpp:1622
std::vector< std::string > parenthetical_split(const std::string &val, const char separator, const std::string &left, const std::string &right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...
bool remove_attack(attack_ptr atk)
Remove an attack from the unit.
Definition: unit.cpp:2478