The Battle for Wesnoth  1.15.3+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  , special_notes_(o.special_notes_)
362  , usage_(copy_or_null(o.usage_))
363  , halo_(copy_or_null(o.halo_))
364  , ellipse_(copy_or_null(o.ellipse_))
365  , random_traits_(o.random_traits_)
366  , generate_name_(o.generate_name_)
367  , upkeep_(o.upkeep_)
368  , profile_(o.profile_)
369  , small_profile_(o.small_profile_)
370  , changed_attributes_(o.changed_attributes_)
371  , invisibility_cache_()
372 {
373  // Copy the attacks rather than just copying references
374  for(auto& a : attacks_) {
375  a.reset(new attack_type(*a));
376  }
377 }
378 
380  : ref_count_(0)
381  , loc_()
382  , advances_to_()
383  , type_(nullptr)
384  , type_name_()
385  , race_(&unit_race::null_race)
386  , id_()
387  , name_()
388  , underlying_id_(0)
390  , variation_()
391  , hit_points_(1)
392  , max_hit_points_(1)
393  , experience_(0)
394  , max_experience_(1)
395  , level_(0)
396  , recall_cost_(-1)
397  , canrecruit_(false)
398  , recruit_list_()
399  , alignment_()
400  , flag_rgb_()
401  , image_mods_()
402  , unrenamable_(false)
403  , side_(0)
404  , gender_(unit_race::NUM_GENDERS)
406  , movement_(0)
407  , max_movement_(0)
408  , vision_(-1)
409  , jamming_(0)
410  , movement_type_()
411  , hold_position_(false)
412  , end_turn_(false)
413  , resting_(false)
414  , attacks_left_(0)
415  , max_attacks_(0)
416  , states_()
418  , variables_()
419  , events_()
420  , filter_recall_()
421  , emit_zoc_(0)
422  , overlays_()
423  , role_()
424  , attacks_()
425  , facing_(map_location::NDIRECTIONS)
426  , trait_names_()
428  , unit_value_()
429  , goto_()
431  , is_fearless_(false)
432  , is_healthy_(false)
435  , hidden_(false)
436  , hp_bar_scaling_(0)
437  , xp_bar_scaling_(0)
438  , modifications_()
439  , abilities_()
440  , advancements_()
441  , description_()
442  , special_notes_()
443  , usage_()
444  , halo_()
445  , ellipse_()
446  , random_traits_(true)
447  , generate_name_(true)
448  , upkeep_(upkeep_full())
451 {
452 
453 }
454 
455 void unit::init(const config& cfg, bool use_traits, const vconfig* vcfg)
456 {
457  loc_ = map_location(cfg["x"], cfg["y"], wml_loc());
458  type_ = &get_unit_type(cfg["parent_type"].blank() ? cfg["type"].str() : cfg["parent_type"].str());
460  id_ = cfg["id"].str();
461  name_ = cfg["name"].t_str();
462  variation_ = cfg["variation"].empty() ? type_->default_variation() : cfg["variation"].str();
463  canrecruit_ = cfg["canrecruit"].to_bool();
464  gender_ = generate_gender(*type_, cfg);
465  role_ = cfg["role"].str();
466  //, facing_(map_location::NDIRECTIONS)
467  //, anim_comp_(new unit_animation_component(*this))
468  hidden_ = cfg["hidden"].to_bool(false);
469  hp_bar_scaling_ = cfg["hp_bar_scaling"].blank() ? type_->hp_bar_scaling() : cfg["hp_bar_scaling"];
470  xp_bar_scaling_ = cfg["xp_bar_scaling"].blank() ? type_->xp_bar_scaling() : cfg["xp_bar_scaling"];
471  random_traits_ = true;
472  generate_name_ = true;
473  side_ = cfg["side"].to_int();
474 
475  if(side_ <= 0) {
476  side_ = 1;
477  }
478 
480  underlying_id_ = n_unit::unit_id(cfg["underlying_id"].to_size_t());
482 
483  if(vcfg) {
484  const vconfig& filter_recall = vcfg->child("filter_recall");
485  if(!filter_recall.null())
486  filter_recall_ = filter_recall.get_config();
487 
488  const vconfig::child_list& events = vcfg->get_children("event");
489  for(const vconfig& e : events) {
490  events_.add_child("event", e.get_config());
491  }
492  } else {
493  filter_recall_ = cfg.child_or_empty("filter_recall");
494 
495  for(const config& unit_event : cfg.child_range("event")) {
496  events_.add_child("event", unit_event);
497  }
498  }
499 
502  }
503 
504  random_traits_ = cfg["random_traits"].to_bool(true);
505  facing_ = map_location::parse_direction(cfg["facing"]);
507 
508  if(const config& mods = cfg.child("modifications")) {
509  modifications_ = mods;
510  }
511 
512  generate_name_ = cfg["generate_name"].to_bool(true);
513 
514  // Apply the unit type's data to this unit.
515  advance_to(*type_, use_traits);
516 
517  if(const config::attribute_value* v = cfg.get("overlays")) {
518  auto overlays = utils::parenthetical_split(v->str(), ',');
519  if(overlays.size() > 0) {
520  deprecated_message("[unit]overlays", DEP_LEVEL::PREEMPTIVE, {1, 17, 0}, "This warning is only triggered by the cases that *do* still work: setting [unit]overlays= works, but the [unit]overlays attribute will always be empty if WML tries to read it.");
521  config effect;
522  config o;
523  effect["apply_to"] = "overlay";
524  effect["add"] = v->str();
525  o.add_child("effect", effect);
526  add_modification("object", o);
527  }
528  }
529 
530  if(const config& variables = cfg.child("variables")) {
532  }
533 
534  if(const config::attribute_value* v = cfg.get("race")) {
535  if(const unit_race *r = unit_types.find_race(*v)) {
536  race_ = r;
537  } else {
539  }
540  }
541 
542  if(const config::attribute_value* v = cfg.get("level")) {
543  set_level(v->to_int(level_));
544  }
545 
546  if(const config::attribute_value* v = cfg.get("undead_variation")) {
547  set_undead_variation(v->str());
548  }
549 
550  if(const config::attribute_value* v = cfg.get("max_attacks")) {
551  set_max_attacks(std::max(0, v->to_int(1)));
552  }
553 
554  if(const config::attribute_value* v = cfg.get("zoc")) {
555  set_emit_zoc(v->to_bool(level_ > 0));
556  }
557 
558  if(const config::attribute_value* v = cfg.get("description")) {
559  description_ = *v;
560  }
561 
562  if(const config::attribute_value* v = cfg.get("cost")) {
563  unit_value_ = *v;
564  }
565 
566  if(const config::attribute_value* v = cfg.get("ellipse")) {
567  set_image_ellipse(*v);
568  }
569 
570  if(const config::attribute_value* v = cfg.get("halo")) {
571  set_image_halo(*v);
572  }
573 
574  if(const config::attribute_value* v = cfg.get("usage")) {
575  set_usage(*v);
576  }
577 
578  if(const config::attribute_value* v = cfg.get("profile")) {
579  set_big_profile(v->str());
580  }
581 
582  if(const config::attribute_value* v = cfg.get("small_profile")) {
583  set_small_profile(v->str());
584  }
585 
586  if(const config::attribute_value* v = cfg.get("max_hitpoints")) {
587  set_max_hitpoints(std::max(1, v->to_int(max_hit_points_)));
588  }
589  if(const config::attribute_value* v = cfg.get("max_moves")) {
590  set_total_movement(std::max(1, v->to_int(max_movement_)));
591  }
592  if(const config::attribute_value* v = cfg.get("max_experience")) {
593  set_max_experience(std::max(1, v->to_int(max_experience_)));
594  }
595 
596  vision_ = cfg["vision"].to_int(vision_);
597  jamming_ = cfg["jamming"].to_int(jamming_);
598 
599  advances_to_t temp_advances = utils::split(cfg["advances_to"]);
600  if(temp_advances.size() == 1 && temp_advances.front() == "null") {
602  } else if(temp_advances.size() >= 1 && !temp_advances.front().empty()) {
603  set_advances_to(temp_advances);
604  }
605 
606  if(const config& ai = cfg.child("ai")) {
607  formula_man_->read(ai);
608  }
609 
610  // Don't use the unit_type's attacks if this config has its own defined
611  if(config::const_child_itors cfg_range = cfg.child_range("attack")) {
613  attacks_.clear();
614  for(const config& c : cfg_range) {
615  attacks_.emplace_back(new attack_type(c));
616  }
617  }
618 
619  // Don't use the unit_type's special notes if this config has its own defined
620  if(config::const_child_itors cfg_range = cfg.child_range("special_note")) {
622  special_notes_.clear();
623  for(const config& c : cfg_range) {
624  special_notes_.emplace_back(c["note"].t_str());
625  }
626  }
627 
628  // If cfg specifies [advancement]s, replace this [advancement]s with them.
629  if(cfg.has_child("advancement")) {
631  this->advancements_.clear();
632  boost::copy(cfg.child_range("advancement"), boost::make_function_output_iterator(ptr_vector_pushback(advancements_)));
633  }
634 
635  // Don't use the unit_type's abilities if this config has its own defined
636  // Why do we allow multiple [abilities] tags?
637  if(config::const_child_itors cfg_range = cfg.child_range("abilities")) {
639  abilities_.clear();
640  for(const config& abilities : cfg_range) {
641  this->abilities_.append(abilities);
642  }
643  }
644 
645  if(const config::attribute_value* v = cfg.get("alignment")) {
647  alignment_.parse(v->str());
648  }
649 
650  // Adjust the unit's defense, movement, vision, jamming, resistances, and
651  // flying status if this config has its own defined.
652  if(cfg.has_child("movement_costs")
653  || cfg.has_child("vision_costs")
654  || cfg.has_child("jamming_costs")
655  || cfg.has_child("defense")
656  || cfg.has_child("resistance")
657  || cfg.has_attribute("flying"))
658  {
660  }
661 
662  movement_type_.merge(cfg);
663 
664  if(const config& status_flags = cfg.child("status")) {
665  for(const config::attribute &st : status_flags.attribute_range()) {
666  if(st.second.to_bool()) {
667  set_state(st.first, true);
668  }
669  }
670  }
671 
672  if(cfg["ai_special"] == "guardian") {
673  set_state(STATE_GUARDIAN, true);
674  }
675 
676  if(const config::attribute_value* v = cfg.get("invulnerable")) {
677  set_state("invulnerable", v->to_bool());
678  }
679 
680  goto_.set_wml_x(cfg["goto_x"].to_int());
681  goto_.set_wml_y(cfg["goto_y"].to_int());
682 
683  attacks_left_ = std::max(0, cfg["attacks_left"].to_int(max_attacks_));
684 
685  movement_ = std::max(0, cfg["moves"].to_int(max_movement_));
686  // we allow negative hitpoints, one of the reasons is that a unit
687  // might be stored+unstored during a attack related event before it
688  // dies when it has negative hp and when dont want the event to
689  // change the unit hp when it was not intended.
690  hit_points_ = cfg["hitpoints"].to_int(max_hit_points_);
691 
692  experience_ = cfg["experience"];
693  resting_ = cfg["resting"].to_bool();
694  unrenamable_ = cfg["unrenamable"].to_bool();
695 
696  // We need to check to make sure that the cfg is not blank and if it
697  // isn't pull that value otherwise it goes with the default of -1.
698  if(!cfg["recall_cost"].blank()) {
699  recall_cost_ = cfg["recall_cost"].to_int(recall_cost_);
700  }
701 
702  generate_name();
703 
704  parse_upkeep(cfg["upkeep"]);
705 
706  set_recruits(utils::split(cfg["extra_recruit"]));
707 
709  warn_unknown_attribute(cfg.attribute_range());
710 
711 #if 0
712  // Debug unit animations for units as they appear in game
713  for(const auto& anim : anim_comp_->animations_) {
714  std::cout << anim.debug() << std::endl;
715  }
716 #endif
717 }
718 
720 {
721  for(auto& u : units_with_cache) {
722  u->clear_visibility_cache();
723  }
724 
725  units_with_cache.clear();
726 }
727 
728 void unit::init(const unit_type& u_type, int side, bool real_unit, unit_race::GENDER gender)
729 {
730  type_ = &u_type;
733  side_ = side;
734  gender_ = gender != unit_race::NUM_GENDERS ? gender : generate_gender(u_type, real_unit);
736  upkeep_ = upkeep_full();
737 
738  // Apply the unit type's data to this unit.
739  advance_to(u_type, real_unit);
740 
741  if(real_unit) {
742  generate_name();
743  }
744 
746 
747  // Set these after traits and modifications have set the maximums.
751 }
752 
754 {
755  try {
756  anim_comp_->clear_haloes();
757 
758  // Remove us from the status cache
759  auto itor = std::find(units_with_cache.begin(), units_with_cache.end(), this);
760 
761  if(itor != units_with_cache.end()) {
762  units_with_cache.erase(itor);
763  }
764  } catch(const std::exception & e) {
765  ERR_UT << "Caught exception when destroying unit: " << e.what() << std::endl;
766  } catch(...) {}
767 }
768 
769 /**
770  * Swap, for copy and swap idiom
771  */
772 void unit::swap(unit & o)
773 {
774  using std::swap;
775 
776  // Don't swap reference count, or it will be incorrect...
777  swap(loc_, o.loc_);
779  swap(type_, o.type_);
781  swap(race_, o.race_);
782  swap(id_, o.id_);
783  swap(name_, o.name_);
791  swap(level_, o.level_);
799  swap(side_, o.side_);
800  swap(gender_, o.gender_);
804  swap(vision_, o.vision_);
805  swap(jamming_, o.jamming_);
809  swap(resting_, o.resting_);
812  swap(states_, o.states_);
815  swap(events_, o.events_);
819  swap(role_, o.role_);
820  swap(attacks_, o.attacks_);
821  swap(facing_, o.facing_);
825  swap(goto_, o.goto_);
831  swap(hidden_, o.hidden_);
834 }
835 
837 {
838  if(!name_.empty() || !generate_name_) {
839  return;
840  }
842  generate_name_ = false;
843 }
844 
845 void unit::generate_traits(bool must_have_only)
846 {
847  LOG_UT << "Generating a trait for unit type " << type().log_id() << " with must_have_only " << must_have_only << std::endl;
848  const unit_type& u_type = type();
849 
850  // Calculate the unit's traits
851  config::const_child_itors current_traits = modifications_.child_range("trait");
852  std::vector<const config*> candidate_traits;
853 
854  for(const config& t : u_type.possible_traits()) {
855  // Skip the trait if the unit already has it.
856  const std::string& tid = t["id"];
857  bool already = false;
858  for(const config& mod : current_traits) {
859  if(mod["id"] == tid) {
860  already = true;
861  break;
862  }
863  }
864 
865  if(already) {
866  continue;
867  }
868 
869  // Add the trait if it is mandatory.
870  const std::string& avl = t["availability"];
871  if(avl == "musthave") {
872  modifications_.add_child("trait", t);
873  current_traits = modifications_.child_range("trait");
874  continue;
875  }
876 
877  // The trait is still available, mark it as a candidate for randomizing.
878  // For leaders, only traits with availability "any" are considered.
879  if(!must_have_only && (!can_recruit() || avl == "any")) {
880  candidate_traits.push_back(&t);
881  }
882  }
883 
884  if(must_have_only) return;
885 
886  // Now randomly fill out to the number of traits required or until
887  // there aren't any more traits.
888  int nb_traits = current_traits.size();
889  int max_traits = u_type.num_traits();
890  for(; nb_traits < max_traits && !candidate_traits.empty(); ++nb_traits)
891  {
892  int num = randomness::generator->get_random_int(0,candidate_traits.size()-1);
893  modifications_.add_child("trait", *candidate_traits[num]);
894  candidate_traits.erase(candidate_traits.begin() + num);
895  }
896 
897  // Once random traits are added, don't do it again.
898  // Such as when restoring a saved character.
899  random_traits_ = false;
900 }
901 
902 std::vector<std::string> unit::get_traits_list() const
903 {
904  std::vector<std::string> res;
905 
906  for(const config& mod : modifications_.child_range("trait"))
907  {
908  // Make sure to return empty id trait strings as otherwise
909  // names will not match in length (Bug #21967)
910  res.push_back(mod["id"]);
911  }
912  return res;
913 }
914 
915 
916 /**
917  * Advances this unit to the specified type.
918  * Experience is left unchanged.
919  * Current hit point total is left unchanged unless it would violate max HP.
920  * Assumes gender_ and variation_ are set to their correct values.
921  */
922 void unit::advance_to(const unit_type& u_type, bool use_traits)
923 {
924  appearance_changed_ = true;
925  // For reference, the type before this advancement.
926  const unit_type& old_type = type();
927  // Adjust the new type for gender and variation.
929  // In cast u_type was already a variation, make sure our variation is set correctly.
930  variation_ = new_type.variation_id();
931 
932  // Reset the scalar values first
933  trait_names_.clear();
934  trait_descriptions_.clear();
935  is_fearless_ = false;
936  is_healthy_ = false;
937  image_mods_.clear();
938  overlays_.clear();
939  ellipse_.reset();
940 
941  // Clear modification-related caches
943 
944  // build unit type ready to create units. Not sure if needed.
945  new_type.get_cfg_for_units();
946 
947  if(!new_type.usage().empty()) {
948  set_usage(new_type.usage());
949  }
950 
951  set_image_halo(new_type.halo());
952  if(!new_type.ellipse().empty()) {
953  set_image_ellipse(new_type.ellipse());
954  }
955 
956  generate_name_ &= new_type.generate_name();
957  abilities_ = new_type.abilities_cfg();
958  advancements_.clear();
959 
960  for(const config& advancement : new_type.advancements()) {
961  advancements_.push_back(new config(advancement));
962  }
963 
964  // If unit has specific profile, remember it and keep it after advancing
965  if(small_profile_.empty() || small_profile_ == old_type.small_profile()) {
966  small_profile_ = new_type.small_profile();
967  }
968 
969  if(profile_.empty() || profile_ == old_type.big_profile()) {
970  profile_ = new_type.big_profile();
971  }
972  // NOTE: There should be no need to access old_cfg (or new_cfg) after this
973  // line. Particularly since the swap might have affected old_cfg.
974 
975  advances_to_ = new_type.advances_to();
976 
977  race_ = new_type.race();
978  type_ = &new_type;
979  type_name_ = new_type.type_name();
980  description_ = new_type.unit_description();
981  special_notes_ = new_type.special_notes();
982  undead_variation_ = new_type.undead_variation();
983  max_experience_ = new_type.experience_needed(true);
984  level_ = new_type.level();
985  recall_cost_ = new_type.recall_cost();
986  alignment_ = new_type.alignment();
987  max_hit_points_ = new_type.hitpoints();
988  hp_bar_scaling_ = new_type.hp_bar_scaling();
989  xp_bar_scaling_ = new_type.xp_bar_scaling();
990  max_movement_ = new_type.movement();
991  vision_ = new_type.vision(true);
992  jamming_ = new_type.jamming();
993  movement_type_ = new_type.movement_type();
994  emit_zoc_ = new_type.has_zoc();
995  attacks_.clear();
996  std::transform(new_type.attacks().begin(), new_type.attacks().end(), std::back_inserter(attacks_), [](const attack_type& atk) {
997  return std::make_shared<attack_type>(atk);
998  });
999  unit_value_ = new_type.cost();
1000 
1001  max_attacks_ = new_type.max_attacks();
1002 
1003  flag_rgb_ = new_type.flag_rgb();
1004 
1005  upkeep_ = upkeep_full();
1006  parse_upkeep(new_type.get_cfg()["upkeep"]);
1007 
1008  anim_comp_->reset_after_advance(&new_type);
1009 
1010  if(random_traits_) {
1011  generate_traits(!use_traits);
1012  } else {
1013  // This will add any "musthave" traits to the new unit that it doesn't already have.
1014  // This covers the Dark Sorcerer advancing to Lich and gaining the "undead" trait,
1015  // but random and/or optional traits are not added,
1016  // and neither are inappropriate traits removed.
1017  generate_traits(true);
1018  }
1019 
1020  // Apply modifications etc, refresh the unit.
1021  // This needs to be after type and gender are fixed,
1022  // since there can be filters on the modifications
1023  // that may result in different effects after the advancement.
1025 
1026  // Now that modifications are done modifying traits, check if poison should
1027  // be cleared.
1028  if(get_state("unpoisonable")) {
1029  set_state(STATE_POISONED, false);
1030  }
1031 
1032  // Now that modifications are done modifying the maximum hit points,
1033  // enforce this maximum.
1036  }
1037 
1038  // In case the unit carries EventWML, apply it now
1040  resources::game_events->add_events(new_type.events(), new_type.id());
1041  }
1042  bool bool_small_profile = get_attr_changed(UA_SMALL_PROFILE);
1043  bool bool_profile = get_attr_changed(UA_PROFILE);
1045  if(bool_small_profile && small_profile_ != new_type.small_profile()) {
1047  }
1048 
1049  if(bool_profile && profile_ != new_type.big_profile()) {
1051  }
1052 }
1053 
1054 std::string unit::big_profile() const
1055 {
1056  if(!profile_.empty() && profile_ != "unit_image") {
1057  return profile_;
1058  }
1059 
1060  return absolute_image();
1061 }
1062 
1063 std::string unit::small_profile() const
1064 {
1065  if(!small_profile_.empty() && small_profile_ != "unit_image") {
1066  return small_profile_;
1067  }
1068 
1069  if(!profile_.empty() && small_profile_ != "unit_image" && profile_ != "unit_image") {
1070  return profile_;
1071  }
1072 
1073  return absolute_image();
1074 }
1075 
1076 const std::string& unit::leader_crown()
1077 {
1078  return leader_crown_path;
1079 }
1080 
1081 const std::string& unit::flag_rgb() const
1082 {
1083  return flag_rgb_.empty() ? game_config::unit_rgb : flag_rgb_;
1084 }
1085 
1087 {
1088  double unit_energy = 0.0;
1089  color_t energy_color {0,0,0,255};
1090 
1091  if(max_hitpoints > 0) {
1092  unit_energy = static_cast<double>(hitpoints)/static_cast<double>(max_hitpoints);
1093  }
1094 
1095  if(1.0 == unit_energy) {
1096  energy_color.r = 33;
1097  energy_color.g = 225;
1098  energy_color.b = 0;
1099  } else if(unit_energy > 1.0) {
1100  energy_color.r = 100;
1101  energy_color.g = 255;
1102  energy_color.b = 100;
1103  } else if(unit_energy >= 0.75) {
1104  energy_color.r = 170;
1105  energy_color.g = 255;
1106  energy_color.b = 0;
1107  } else if(unit_energy >= 0.5) {
1108  energy_color.r = 255;
1109  energy_color.g = 175;
1110  energy_color.b = 0;
1111  } else if(unit_energy >= 0.25) {
1112  energy_color.r = 255;
1113  energy_color.g = 155;
1114  energy_color.b = 0;
1115  } else {
1116  energy_color.r = 255;
1117  energy_color.g = 0;
1118  energy_color.b = 0;
1119  }
1120 
1121  return energy_color;
1122 }
1123 
1125 {
1126  return hp_color_impl(hitpoints(), max_hitpoints());
1127 }
1128 
1129 color_t unit::hp_color(int new_hitpoints) const
1130 {
1131  return hp_color_impl(new_hitpoints, hitpoints());
1132 }
1133 
1135 {
1136  return hp_color_impl(1, 1);
1137 }
1138 
1140 {
1141  const color_t near_advance_color {255,255,255,255};
1142  const color_t mid_advance_color {150,255,255,255};
1143  const color_t far_advance_color {0,205,205,255};
1144  const color_t normal_color {0,160,225,255};
1145  const color_t near_amla_color {225,0,255,255};
1146  const color_t mid_amla_color {169,30,255,255};
1147  const color_t far_amla_color {139,0,237,255};
1148  const color_t amla_color {170,0,255,255};
1149 
1150  const bool near_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience;
1151  const bool mid_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience*2;
1152  const bool far_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience*3;
1153 
1154  color_t color = normal_color;
1155  if(can_advance){
1156  if(near_advance){
1157  color=near_advance_color;
1158  } else if(mid_advance){
1159  color=mid_advance_color;
1160  } else if(far_advance){
1161  color=far_advance_color;
1162  }
1163  } else if(has_amla){
1164  if(near_advance){
1165  color=near_amla_color;
1166  } else if(mid_advance){
1167  color=mid_amla_color;
1168  } else if(far_advance){
1169  color=far_amla_color;
1170  } else {
1171  color=amla_color;
1172  }
1173  }
1174 
1175  return(color);
1176 }
1177 
1179 {
1180  bool major_amla = false;
1181  bool has_amla = false;
1182  for(const config& adv:get_modification_advances()){
1183  major_amla |= adv["major_amla"].to_bool();
1184  has_amla = true;
1185  }
1186  return xp_color(experience_to_advance(), !advances_to().empty() || major_amla, has_amla);
1187 }
1188 
1189 void unit::set_recruits(const std::vector<std::string>& recruits)
1190 {
1191  unit_types.check_types(recruits);
1193  //TODO crab
1194  //info_.minimum_recruit_price = 0;
1195  //ai::manager::get_singleton().raise_recruit_list_changed();
1196 }
1197 
1198 const std::vector<std::string> unit::advances_to_translated() const
1199 {
1200  std::vector<std::string> result;
1201  for(const std::string& adv_type_id : advances_to_) {
1202  if(const unit_type* adv_type = unit_types.find(adv_type_id)) {
1203  result.push_back(adv_type->type_name());
1204  } else {
1205  WRN_UT << "unknown unit in advances_to list of type "
1206  << type().log_id() << ": " << adv_type_id << std::endl;
1207  }
1208  }
1209 
1210  return result;
1211 }
1212 
1213 void unit::set_advances_to(const std::vector<std::string>& advances_to)
1214 {
1216  unit_types.check_types(advances_to);
1218 }
1219 
1220 void unit::set_movement(int moves, bool unit_action)
1221 {
1222  // If this was because the unit acted, clear its "not acting" flags.
1223  if(unit_action) {
1224  end_turn_ = hold_position_ = false;
1225  }
1226 
1227  movement_ = std::max<int>(0, moves);
1228 }
1229 
1230 /**
1231  * Determines if @a mod_dur "matches" @a goal_dur.
1232  * If goal_dur is not empty, they match if they are equal.
1233  * If goal_dur is empty, they match if mod_dur is neither empty nor "forever".
1234  * Helper function for expire_modifications().
1235  */
1236 inline bool mod_duration_match(const std::string& mod_dur, const std::string& goal_dur)
1237 {
1238  if(goal_dur.empty()) {
1239  // Default is all temporary modifications.
1240  return !mod_dur.empty() && mod_dur != "forever";
1241  }
1242 
1243  return mod_dur == goal_dur;
1244 }
1245 
1246 void unit::expire_modifications(const std::string& duration)
1247 {
1248  // If any modifications expire, then we will need to rebuild the unit.
1249  const unit_type* rebuild_from = nullptr;
1250  int hp = hit_points_;
1251  int mp = movement_;
1252  // Loop through all types of modifications.
1253  for(const auto& mod_name : ModificationTypes) {
1254  // Loop through all modifications of this type.
1255  // Looping in reverse since we may delete the current modification.
1256  for(int j = modifications_.child_count(mod_name)-1; j >= 0; --j)
1257  {
1258  const config& mod = modifications_.child(mod_name, j);
1259 
1260  if(mod_duration_match(mod["duration"], duration)) {
1261  // If removing this mod means reverting the unit's type:
1262  if(const config::attribute_value* v = mod.get("prev_type")) {
1263  rebuild_from = &get_unit_type(v->str());
1264  }
1265  // Else, if we have not already specified a type to build from:
1266  else if(rebuild_from == nullptr) {
1267  rebuild_from = &type();
1268  }
1269 
1270  modifications_.remove_child(mod_name, j);
1271  }
1272  }
1273  }
1274 
1275  if(rebuild_from != nullptr) {
1276  anim_comp_->clear_haloes();
1277  advance_to(*rebuild_from);
1278  hit_points_ = hp;
1279  movement_ = std::min(mp, max_movement_);
1280  }
1281 }
1282 
1284 {
1285  expire_modifications("turn");
1286 
1290  set_state(STATE_UNCOVERED, false);
1291 }
1292 
1294 {
1295  expire_modifications("turn end");
1296 
1297  set_state(STATE_SLOWED,false);
1299  resting_ = false;
1300  }
1301 
1302  set_state(STATE_NOT_MOVED,false);
1303  // Clear interrupted move
1305 }
1306 
1308 {
1309  // Set the goto-command to be going to no-where
1310  goto_ = map_location();
1311 
1312  // Expire all temporary modifications.
1314 
1315  heal_fully();
1316  set_state(STATE_SLOWED, false);
1317  set_state(STATE_POISONED, false);
1318  set_state(STATE_PETRIFIED, false);
1319  set_state(STATE_GUARDIAN, false);
1320 }
1321 
1322 void unit::heal(int amount)
1323 {
1324  int max_hp = max_hitpoints();
1325  if(hit_points_ < max_hp) {
1326  hit_points_ += amount;
1327 
1328  if(hit_points_ > max_hp) {
1329  hit_points_ = max_hp;
1330  }
1331  }
1332 
1333  if(hit_points_<1) {
1334  hit_points_ = 1;
1335  }
1336 }
1337 
1338 const std::set<std::string> unit::get_states() const
1339 {
1340  std::set<std::string> all_states = states_;
1341  for(const auto& state : known_boolean_state_names_) {
1342  if(get_state(state.second)) {
1343  all_states.insert(state.first);
1344  }
1345  }
1346 
1347  // Backwards compatibility for not_living. Don't remove before 1.12
1348  if(all_states.count("undrainable") && all_states.count("unpoisonable") && all_states.count("unplagueable")) {
1349  all_states.insert("not_living");
1350  }
1351 
1352  return all_states;
1353 }
1354 
1355 bool unit::get_state(const std::string& state) const
1356 {
1357  state_t known_boolean_state_id = get_known_boolean_state_id(state);
1358  if(known_boolean_state_id!=STATE_UNKNOWN){
1359  return get_state(known_boolean_state_id);
1360  }
1361 
1362  // Backwards compatibility for not_living. Don't remove before 1.12
1363  if(state == "not_living") {
1364  return
1365  get_state("undrainable") &&
1366  get_state("unpoisonable") &&
1367  get_state("unplagueable");
1368  }
1369 
1370  return states_.find(state) != states_.end();
1371 }
1372 
1373 void unit::set_state(state_t state, bool value)
1374 {
1375  known_boolean_states_[state] = value;
1376 }
1377 
1378 bool unit::get_state(state_t state) const
1379 {
1380  return known_boolean_states_[state];
1381 }
1382 
1384 {
1385  auto i = known_boolean_state_names_.find(state);
1386  if(i != known_boolean_state_names_.end()) {
1387  return i->second;
1388  }
1389 
1390  return STATE_UNKNOWN;
1391 }
1392 
1393 std::map<std::string, unit::state_t> unit::known_boolean_state_names_ {
1394  {"slowed", STATE_SLOWED},
1395  {"poisoned", STATE_POISONED},
1396  {"petrified", STATE_PETRIFIED},
1397  {"uncovered", STATE_UNCOVERED},
1398  {"not_moved", STATE_NOT_MOVED},
1399  {"unhealable", STATE_UNHEALABLE},
1400  {"guardian", STATE_GUARDIAN},
1401 };
1402 
1403 void unit::set_state(const std::string& state, bool value)
1404 {
1405  appearance_changed_ = true;
1406  state_t known_boolean_state_id = get_known_boolean_state_id(state);
1407  if(known_boolean_state_id != STATE_UNKNOWN) {
1408  set_state(known_boolean_state_id, value);
1409  return;
1410  }
1411 
1412  // Backwards compatibility for not_living. Don't remove before 1.12
1413  if(state == "not_living") {
1414  set_state("undrainable", value);
1415  set_state("unpoisonable", value);
1416  set_state("unplagueable", value);
1417  }
1418 
1419  if(value) {
1420  states_.insert(state);
1421  } else {
1422  states_.erase(state);
1423  }
1424 }
1425 
1426 bool unit::has_ability_by_id(const std::string& ability) const
1427 {
1428  for(const config::any_child &ab : this->abilities_.all_children_range()) {
1429  if(ab.cfg["id"] == ability) {
1430  return true;
1431  }
1432  }
1433 
1434  return false;
1435 }
1436 
1437 void unit::remove_ability_by_id(const std::string& ability)
1438 {
1441  while (i != this->abilities_.ordered_end()) {
1442  if(i->cfg["id"] == ability) {
1443  i = this->abilities_.erase(i);
1444  } else {
1445  ++i;
1446  }
1447  }
1448 }
1449 
1451 {
1452  for(const auto& a_ptr : attacks_) {
1453  if(a_ptr->get_changed()) {
1454  return true;
1455  }
1456 
1457  }
1458  return false;
1459 }
1460 void unit::write(config& cfg, bool write_all) const
1461 {
1462  config back;
1463  auto write_subtag = [&](const std::string& key, const config& child)
1464  {
1465  cfg.clear_children(key);
1466 
1467  if(!child.empty()) {
1468  cfg.add_child(key, child);
1469  } else {
1470  back.add_child(key, child);
1471  }
1472  };
1473 
1474  if(write_all || get_attr_changed(UA_MOVEMENT_TYPE)) {
1475  movement_type_.write(cfg);
1476  }
1477  if(write_all || get_attr_changed(UA_SMALL_PROFILE)) {
1478  cfg["small_profile"] = small_profile_;
1479  }
1480  if(write_all || get_attr_changed(UA_PROFILE)) {
1481  cfg["profile"] = profile_;
1482  }
1483  if(description_ != type().unit_description()) {
1484  cfg["description"] = description_;
1485  }
1486  if(write_all || get_attr_changed(UA_NOTES)) {
1487  for(const t_string& note : special_notes_) {
1488  cfg.add_child("special_note")["note"] = note;
1489  }
1490  }
1491 
1492  if(halo_.get()) {
1493  cfg["halo"] = *halo_;
1494  }
1495 
1496  if(ellipse_.get()) {
1497  cfg["ellipse"] = *ellipse_;
1498  }
1499 
1500  if(usage_.get()) {
1501  cfg["usage"] = *usage_;
1502  }
1503 
1504  write_upkeep(cfg["upkeep"]);
1505 
1506  cfg["hitpoints"] = hit_points_;
1507  if(write_all || get_attr_changed(UA_MAX_HP)) {
1508  cfg["max_hitpoints"] = max_hit_points_;
1509  }
1510  cfg["image_icon"] = type().icon();
1511  cfg["image"] = type().image();
1512  cfg["random_traits"] = random_traits_;
1513  cfg["generate_name"] = generate_name_;
1514  cfg["experience"] = experience_;
1515  if(write_all || get_attr_changed(UA_MAX_XP)) {
1516  cfg["max_experience"] = max_experience_;
1517  }
1518  cfg["recall_cost"] = recall_cost_;
1519 
1520  cfg["side"] = side_;
1521 
1522  cfg["type"] = type_id();
1523 
1524  if(type_id() != type().base_id()) {
1525  cfg["parent_type"] = type().base_id();
1526  }
1527 
1528  // Support for unit formulas in [ai] and unit-specific variables in [ai] [vars]
1529  formula_man_->write(cfg);
1530 
1531  cfg["gender"] = gender_string(gender_);
1532  cfg["variation"] = variation_;
1533  cfg["role"] = role_;
1534 
1535  config status_flags;
1536  for(const std::string& state : get_states()) {
1537  status_flags[state] = true;
1538  }
1539 
1540  write_subtag("variables", variables_);
1541  write_subtag("filter_recall", filter_recall_);
1542  write_subtag("status", status_flags);
1543 
1544  cfg.clear_children("events");
1545  cfg.append(events_);
1546 
1547  // Overlays are exported as the modifications that add them, not as an overlays= value,
1548  // however removing the key breaks the Gui Debug Tools.
1549  // \todo does anything depend on the key's value, other than the re-import code in unit::init?
1550  cfg["overlays"] = "";
1551 
1552  cfg["name"] = name_;
1553  cfg["id"] = id_;
1554  cfg["underlying_id"] = underlying_id_.value;
1555 
1556  if(can_recruit()) {
1557  cfg["canrecruit"] = true;
1558  }
1559 
1560  cfg["extra_recruit"] = utils::join(recruit_list_);
1561 
1562  cfg["facing"] = map_location::write_direction(facing_);
1563 
1564  cfg["goto_x"] = goto_.wml_x();
1565  cfg["goto_y"] = goto_.wml_y();
1566 
1567  cfg["moves"] = movement_;
1568  if(write_all || get_attr_changed(UA_MAX_MP)) {
1569  cfg["max_moves"] = max_movement_;
1570  }
1571  cfg["vision"] = vision_;
1572  cfg["jamming"] = jamming_;
1573 
1574  cfg["resting"] = resting_;
1575 
1576  if(write_all || get_attr_changed(UA_ADVANCE_TO)) {
1577  cfg["advances_to"] = utils::join(advances_to_);
1578  }
1579 
1580  cfg["race"] = race_->id();
1581  cfg["language_name"] = type_name_;
1582  cfg["undead_variation"] = undead_variation_;
1583  if(write_all || get_attr_changed(UA_LEVEL)) {
1584  cfg["level"] = level_;
1585  }
1586  if(write_all || get_attr_changed(UA_ALIGNMENT)) {
1587  cfg["alignment"] = alignment_.to_string();
1588  }
1589  cfg["flag_rgb"] = flag_rgb_;
1590  cfg["unrenamable"] = unrenamable_;
1591 
1592  cfg["attacks_left"] = attacks_left_;
1593  if(write_all || get_attr_changed(UA_MAX_AP)) {
1594  cfg["max_attacks"] = max_attacks_;
1595  }
1596  if(write_all || get_attr_changed(UA_ZOC)) {
1597  cfg["zoc"] = emit_zoc_;
1598  }
1599  cfg["hidden"] = hidden_;
1600 
1601  if(write_all || get_attr_changed(UA_ATTACKS) || get_attacks_changed()) {
1602  cfg.clear_children("attack");
1603  for(attack_ptr i : attacks_) {
1604  i->write(cfg.add_child("attack"));
1605  }
1606  }
1607 
1608  cfg["cost"] = unit_value_;
1609 
1610  write_subtag("modifications", modifications_);
1611  if(write_all || get_attr_changed(UA_ABILITIES)) {
1612  write_subtag("abilities", abilities_);
1613  }
1614  if(write_all || get_attr_changed(UA_ADVANCEMENTS)) {
1615  cfg.clear_children("advancement");
1616  for(const config& advancement : this->advancements_) {
1617  if(!advancement.empty()) {
1618  cfg.add_child("advancement", advancement);
1619  }
1620  }
1621  }
1622  cfg.append(back);
1623 }
1624 
1626 {
1627  if(dir != map_location::NDIRECTIONS && dir != facing_) {
1628  appearance_changed_ = true;
1629  facing_ = dir;
1630  }
1631  // Else look at yourself (not available so continue to face the same direction)
1632 }
1633 
1634 int unit::upkeep() const
1635 {
1636  // Leaders do not incur upkeep.
1637  if(can_recruit()) {
1638  return 0;
1639  }
1640 
1642 }
1643 
1644 bool unit::loyal() const
1645 {
1646  return boost::get<upkeep_loyal>(&upkeep_) != nullptr;
1647 }
1648 
1650 {
1651  int def = movement_type_.defense_modifier(terrain);
1652 #if 0
1653  // A [defense] ability is too costly and doesn't take into account target locations.
1654  // Left as a comment in case someone ever wonders why it isn't a good idea.
1655  unit_ability_list defense_abilities = get_abilities("defense");
1656  if(!defense_abilities.empty()) {
1657  unit_abilities::effect defense_effect(defense_abilities, def, false);
1658  def = defense_effect.get_composite_value();
1659  }
1660 #endif
1661  return def;
1662 }
1663 
1664 bool unit::resistance_filter_matches(const config& cfg, bool attacker, const std::string& damage_name, int res) const
1665 {
1666  if(!(cfg["active_on"].empty() || (attacker && cfg["active_on"] == "offense") || (!attacker && cfg["active_on"] == "defense"))) {
1667  return false;
1668  }
1669 
1670  const std::string& apply_to = cfg["apply_to"];
1671  if(!apply_to.empty()) {
1672  if(damage_name != apply_to) {
1673  if(apply_to.find(',') != std::string::npos &&
1674  apply_to.find(damage_name) != std::string::npos) {
1675  const std::vector<std::string>& vals = utils::split(apply_to);
1676  if(std::find(vals.begin(),vals.end(),damage_name) == vals.end()) {
1677  return false;
1678  }
1679  } else {
1680  return false;
1681  }
1682  }
1683  }
1684 
1685  if(!unit_abilities::filter_base_matches(cfg, res)) {
1686  return false;
1687  }
1688 
1689  return true;
1690 }
1691 
1692 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
1693 {
1694  int res = movement_type_.resistance_against(damage_name);
1695 
1696  unit_ability_list resistance_abilities = get_abilities("resistance",loc);
1697  for(unit_ability_list::iterator i = resistance_abilities.begin(); i != resistance_abilities.end();) {
1698  if(!resistance_filter_matches(*i->first, attacker, damage_name, 100-res) || (!ability_affects_weapon(*i->first, weapon, false) || !ability_affects_weapon(*i->first, opp_weapon, true))) {
1699  i = resistance_abilities.erase(i);
1700  } else {
1701  ++i;
1702  }
1703  }
1704 
1705  if(!resistance_abilities.empty()) {
1706  unit_abilities::effect resist_effect(resistance_abilities, 100-res, false);
1707 
1708  res = 100 - std::min<int>(
1709  resist_effect.get_composite_value(),
1710  resistance_abilities.highest("max_value").first
1711  );
1712  }
1713 
1714  return res;
1715 }
1716 
1717 std::map<std::string, std::string> unit::advancement_icons() const
1718 {
1719  std::map<std::string,std::string> temp;
1720  if(!can_advance()) {
1721  return temp;
1722  }
1723 
1724  if(!advances_to_.empty()) {
1725  std::ostringstream tooltip;
1726  const std::string& image = game_config::images::level;
1727 
1728  for(const std::string& s : advances_to()) {
1729  if(!s.empty()) {
1730  tooltip << s << std::endl;
1731  }
1732  }
1733 
1734  temp[image] = tooltip.str();
1735  }
1736 
1737  for(const config& adv : get_modification_advances()) {
1738  const std::string& image = adv["image"];
1739  if(image.empty()) {
1740  continue;
1741  }
1742 
1743  std::ostringstream tooltip;
1744  tooltip << temp[image];
1745 
1746  const std::string& tt = adv["description"];
1747  if(!tt.empty()) {
1748  tooltip << tt << std::endl;
1749  }
1750 
1751  temp[image] = tooltip.str();
1752  }
1753 
1754  return(temp);
1755 }
1756 
1757 std::vector<std::pair<std::string, std::string>> unit::amla_icons() const
1758 {
1759  std::vector<std::pair<std::string, std::string>> temp;
1760  std::pair<std::string, std::string> icon; // <image,tooltip>
1761 
1762  for(const config& adv : get_modification_advances()) {
1763  icon.first = adv["icon"].str();
1764  icon.second = adv["description"].str();
1765 
1766  for(unsigned j = 0, j_count = modification_count("advancement", adv["id"]); j < j_count; ++j) {
1767  temp.push_back(icon);
1768  }
1769  }
1770 
1771  return(temp);
1772 }
1773 
1774 std::vector<config> unit::get_modification_advances() const
1775 {
1776  std::vector<config> res;
1777  for(const config& adv : modification_advancements()) {
1778  if(adv["strict_amla"].to_bool() && !advances_to_.empty()) {
1779  continue;
1780  }
1781 
1782  if(modification_count("advancement", adv["id"]) >= static_cast<unsigned>(adv["max_times"].to_int(1))) {
1783  continue;
1784  }
1785 
1786  std::vector<std::string> temp_require = utils::split(adv["require_amla"]);
1787  std::vector<std::string> temp_exclude = utils::split(adv["exclude_amla"]);
1788 
1789  if(temp_require.empty() && temp_exclude.empty()) {
1790  res.push_back(adv);
1791  continue;
1792  }
1793 
1794  std::sort(temp_require.begin(), temp_require.end());
1795  std::sort(temp_exclude.begin(), temp_exclude.end());
1796 
1797  std::vector<std::string> uniq_require, uniq_exclude;
1798 
1799  std::unique_copy(temp_require.begin(), temp_require.end(), std::back_inserter(uniq_require));
1800  std::unique_copy(temp_exclude.begin(), temp_exclude.end(), std::back_inserter(uniq_exclude));
1801 
1802  bool exclusion_found = false;
1803  for(const std::string& s : uniq_exclude) {
1804  int max_num = std::count(temp_exclude.begin(), temp_exclude.end(), s);
1805  int mod_num = modification_count("advancement", s);
1806  if(mod_num >= max_num) {
1807  exclusion_found = true;
1808  break;
1809  }
1810  }
1811 
1812  if(exclusion_found) {
1813  continue;
1814  }
1815 
1816  bool requirements_done = true;
1817  for(const std::string& s : uniq_require) {
1818  int required_num = std::count(temp_require.begin(), temp_require.end(), s);
1819  int mod_num = modification_count("advancement", s);
1820  if(required_num > mod_num) {
1821  requirements_done = false;
1822  break;
1823  }
1824  }
1825 
1826  if(requirements_done) {
1827  res.push_back(adv);
1828  }
1829  }
1830 
1831  return res;
1832 }
1833 
1834 void unit::set_advancements(std::vector<config> advancements)
1835 {
1837  this->advancements_.clear();
1838  for(config& advancement : advancements) {
1839  this->advancements_.push_back(new config());
1840  this->advancements_.back().swap(advancement);
1841  }
1842 }
1843 
1844 std::size_t unit::modification_count(const std::string& mod_type, const std::string& id) const
1845 {
1846  std::size_t res = 0;
1847  for(const config& item : modifications_.child_range(mod_type)) {
1848  if(item["id"] == id) {
1849  ++res;
1850  }
1851  }
1852 
1853  // For backwards compatibility, if asked for "advancement", also count "advance"
1854  if(mod_type == "advancement") {
1855  res += modification_count("advance", id);
1856  }
1857 
1858  return res;
1859 }
1860 
1861 const std::set<std::string> unit::builtin_effects {
1862  "alignment", "attack", "defense", "ellipse", "experience", "fearless",
1863  "halo", "healthy", "hitpoints", "image_mod", "jamming", "jamming_costs",
1864  "loyal", "max_attacks", "max_experience", "movement", "movement_costs",
1865  "new_ability", "new_advancement", "new_animation", "new_attack", "overlay", "profile",
1866  "recall_cost", "remove_ability", "remove_advancement", "remove_attacks", "resistance",
1867  "status", "type", "variation", "vision", "vision_costs", "zoc"
1868 };
1869 
1870 std::string unit::describe_builtin_effect(std::string apply_to, const config& effect)
1871 {
1872  if(apply_to == "attack") {
1873  std::vector<t_string> attack_names;
1874 
1875  std::string desc;
1876  for(attack_ptr a : attacks_) {
1877  bool affected = a->describe_modification(effect, &desc);
1878  if(affected && !desc.empty()) {
1879  attack_names.emplace_back(a->name(), "wesnoth-units");
1880  }
1881  }
1882  if(!attack_names.empty()) {
1883  utils::string_map symbols;
1884  symbols["attack_list"] = utils::format_conjunct_list("", attack_names);
1885  symbols["effect_description"] = desc;
1886  return VGETTEXT("$attack_list|: $effect_description", symbols);
1887  }
1888  } else if(apply_to == "hitpoints") {
1889  const std::string& increase_total = effect["increase_total"];
1890  if(!increase_total.empty()) {
1891  return VGETTEXT(
1892  "<span color=\"$color\">$number_or_percent</span> HP",
1893  {{"number_or_percent", utils::print_modifier(increase_total)}, {"color", increase_total[0] == '-' ? "red" : "green"}});
1894  }
1895  } else {
1896  const std::string& increase = effect["increase"];
1897  if(increase.empty()) {
1898  return "";
1899  }
1900  if(apply_to == "movement") {
1901  return VNGETTEXT(
1902  "<span color=\"$color\">$number_or_percent</span> move",
1903  "<span color=\"$color\">$number_or_percent</span> moves",
1904  std::stoi(increase),
1905  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1906  } else if(apply_to == "vision") {
1907  return VGETTEXT(
1908  "<span color=\"$color\">$number_or_percent</span> vision",
1909  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1910  } else if(apply_to == "jamming") {
1911  return VGETTEXT(
1912  "<span color=\"$color\">$number_or_percent</span> jamming",
1913  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1914  } else if(apply_to == "max_experience") {
1915  // Unlike others, decreasing experience is a *GOOD* thing
1916  return VGETTEXT(
1917  "<span color=\"$color\">$number_or_percent</span> XP to advance",
1918  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "green" : "red"}});
1919  } else if(apply_to == "max_attacks") {
1920  return VNGETTEXT(
1921  "<span color=\"$color\">$number_or_percent</span> attack per turn",
1922  "<span color=\"$color\">$number_or_percent</span> attacks per turn",
1923  std::stoi(increase),
1924  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1925  } else if(apply_to == "recall_cost") {
1926  // Unlike others, decreasing recall cost is a *GOOD* thing
1927  return VGETTEXT(
1928  "<span color=\"$color\">$number_or_percent</span> cost to recall",
1929  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "green" : "red"}});
1930  }
1931  }
1932  return "";
1933 }
1934 
1935 void unit::apply_builtin_effect(std::string apply_to, const config& effect)
1936 {
1937  appearance_changed_ = true;
1938  if(apply_to == "fearless") {
1940  is_fearless_ = effect["set"].to_bool(true);
1941  } else if(apply_to == "healthy") {
1943  is_healthy_ = effect["set"].to_bool(true);
1944  } else if(apply_to == "profile") {
1945  if(const config::attribute_value* v = effect.get("portrait")) {
1946  set_big_profile((*v).str());
1947  }
1948 
1949  if(const config::attribute_value* v = effect.get("small_portrait")) {
1950  set_small_profile((*v).str());
1951  }
1952 
1953  if(const config::attribute_value* v = effect.get("description")) {
1954  description_ = *v;
1955  }
1956 
1957  if(config::const_child_itors cfg_range = effect.child_range("special_note")) {
1958  for(const config& c : cfg_range) {
1959  if(!c["remove"].to_bool()) {
1960  special_notes_.emplace_back(c["note"].t_str());
1961  } else {
1962  auto iter = std::find(special_notes_.begin(), special_notes_.end(), c["note"].t_str());
1963  if(iter != special_notes_.end()) {
1964  special_notes_.erase(iter);
1965  }
1966  }
1967  }
1968  }
1969  } else if(apply_to == "new_attack") {
1971  attacks_.emplace_back(new attack_type(effect));
1972  } else if(apply_to == "remove_attacks") {
1974  auto iter = std::remove_if(attacks_.begin(), attacks_.end(), [&effect](attack_ptr a) {
1975  return a->matches_filter(effect);
1976  });
1977 
1978  attacks_.erase(iter, attacks_.end());
1979  } else if(apply_to == "attack") {
1981  for(attack_ptr a : attacks_) {
1982  a->apply_modification(effect);
1983  }
1984  } else if(apply_to == "hitpoints") {
1985  LOG_UT << "applying hitpoint mod..." << hit_points_ << "/" << max_hit_points_ << std::endl;
1986  const std::string& increase_hp = effect["increase"];
1987  const std::string& increase_total = effect["increase_total"];
1988  const std::string& set_hp = effect["set"];
1989  const std::string& set_total = effect["set_total"];
1990 
1991  // If the hitpoints are allowed to end up greater than max hitpoints
1992  const bool violate_max = effect["violate_maximum"].to_bool();
1993 
1994  if(!set_hp.empty()) {
1995  if(set_hp.back() == '%') {
1996  hit_points_ = lexical_cast_default<int>(set_hp)*max_hit_points_/100;
1997  } else {
1998  hit_points_ = lexical_cast_default<int>(set_hp);
1999  }
2000  }
2001 
2002  if(!set_total.empty()) {
2003  if(set_total.back() == '%') {
2004  set_max_hitpoints(lexical_cast_default<int>(set_total)*max_hit_points_/100);
2005  } else {
2006  set_max_hitpoints(lexical_cast_default<int>(set_total));
2007  }
2008  }
2009 
2010  if(!increase_total.empty()) {
2011  // A percentage on the end means increase by that many percent
2013  }
2014 
2015  if(max_hit_points_ < 1)
2016  set_max_hitpoints(1);
2017 
2018  if(effect["heal_full"].to_bool()) {
2019  heal_fully();
2020  }
2021 
2022  if(!increase_hp.empty()) {
2024  }
2025 
2026  LOG_UT << "modded to " << hit_points_ << "/" << max_hit_points_ << std::endl;
2027  if(hit_points_ > max_hit_points_ && !violate_max) {
2028  LOG_UT << "resetting hp to max" << std::endl;
2030  }
2031 
2032  if(hit_points_ < 1) {
2033  hit_points_ = 1;
2034  }
2035  } else if(apply_to == "movement") {
2036  const std::string& increase = effect["increase"];
2037 
2038  if(!increase.empty()) {
2040  }
2041 
2042  set_total_movement(effect["set"].to_int(max_movement_));
2043 
2044  if(movement_ > max_movement_) {
2046  }
2047  } else if(apply_to == "vision") {
2048  const std::string& increase = effect["increase"];
2049 
2050  if(!increase.empty()) {
2051  const int current_vision = vision_ < 0 ? max_movement_ : vision_;
2052  vision_ = utils::apply_modifier(current_vision, increase, 1);
2053  }
2054 
2055  vision_ = effect["set"].to_int(vision_);
2056  } else if(apply_to == "jamming") {
2057  const std::string& increase = effect["increase"];
2058 
2059  if(!increase.empty()) {
2060  jamming_ = utils::apply_modifier(jamming_, increase, 1);
2061  }
2062 
2063  jamming_ = effect["set"].to_int(jamming_);
2064  } else if(apply_to == "experience") {
2065  const std::string& increase = effect["increase"];
2066  const std::string& set = effect["set"];
2067 
2068  if(!set.empty()) {
2069  if(set.back() == '%') {
2070  experience_ = lexical_cast_default<int>(set)*max_experience_/100;
2071  } else {
2072  experience_ = lexical_cast_default<int>(set);
2073  }
2074  }
2075 
2076  if(increase.empty() == false) {
2078  }
2079  } else if(apply_to == "max_experience") {
2080  const std::string& increase = effect["increase"];
2081  const std::string& set = effect["set"];
2082 
2083  if(set.empty() == false) {
2084  if(set.back() == '%') {
2085  set_max_experience(lexical_cast_default<int>(set)*max_experience_/100);
2086  } else {
2087  set_max_experience(lexical_cast_default<int>(set));
2088  }
2089  }
2090 
2091  if(increase.empty() == false) {
2093  }
2094  } else if(apply_to == upkeep_loyal::type()) {
2095  upkeep_ = upkeep_loyal();
2096  } else if(apply_to == "status") {
2097  const std::string& add = effect["add"];
2098  const std::string& remove = effect["remove"];
2099 
2100  for(const std::string& to_add : utils::split(add))
2101  {
2102  set_state(to_add, true);
2103  }
2104 
2105  for(const std::string& to_remove : utils::split(remove))
2106  {
2107  set_state(to_remove, false);
2108  }
2109  } else if(std::find(movetype::effects.cbegin(), movetype::effects.cend(), apply_to) != movetype::effects.cend()) {
2110  // "movement_costs", "vision_costs", "jamming_costs", "defense", "resistance"
2111  if(const config& ap = effect.child(apply_to)) {
2113  movement_type_.merge(ap, apply_to, effect["replace"].to_bool());
2114  }
2115  } else if(apply_to == "zoc") {
2116  if(const config::attribute_value* v = effect.get("value")) {
2118  emit_zoc_ = v->to_bool();
2119  }
2120  } else if(apply_to == "new_ability") {
2121  if(const config& ab_effect = effect.child("abilities")) {
2123  config to_append;
2124  for(const config::any_child &ab : ab_effect.all_children_range()) {
2125  if(!has_ability_by_id(ab.cfg["id"])) {
2126  to_append.add_child(ab.key, ab.cfg);
2127  }
2128  }
2129  this->abilities_.append(to_append);
2130  }
2131  } else if(apply_to == "remove_ability") {
2132  if(const config& ab_effect = effect.child("abilities")) {
2133  for(const config::any_child &ab : ab_effect.all_children_range()) {
2134  remove_ability_by_id(ab.cfg["id"]);
2135  }
2136  }
2137  } else if(apply_to == "image_mod") {
2138  LOG_UT << "applying image_mod" << std::endl;
2139  std::string mod = effect["replace"];
2140  if(!mod.empty()){
2141  image_mods_ = mod;
2142  }
2143  LOG_UT << "applying image_mod" << std::endl;
2144  mod = effect["add"].str();
2145  if(!mod.empty()){
2146  if(!image_mods_.empty()) {
2147  image_mods_ += '~';
2148  }
2149 
2150  image_mods_ += mod;
2151  }
2152 
2154  LOG_UT << "applying image_mod" << std::endl;
2155  } else if(apply_to == "new_animation") {
2156  anim_comp_->apply_new_animation_effect(effect);
2157  } else if(apply_to == "ellipse") {
2158  set_image_ellipse(effect["ellipse"]);
2159  } else if(apply_to == "halo") {
2160  set_image_halo(effect["halo"]);
2161  } else if(apply_to == "overlay") {
2162  const std::string& add = effect["add"];
2163  const std::string& replace = effect["replace"];
2164  const std::string& remove = effect["remove"];
2165 
2166  if(!add.empty()) {
2167  for(const auto& to_add : utils::parenthetical_split(add, ',')) {
2168  overlays_.push_back(to_add);
2169  }
2170  }
2171  if(!remove.empty()) {
2172  for(const auto& to_remove : utils::parenthetical_split(remove, ',')) {
2173  overlays_.erase(std::remove(overlays_.begin(), overlays_.end(), to_remove), overlays_.end());
2174  }
2175  }
2176  if(add.empty() && remove.empty() && !replace.empty()) {
2177  overlays_ = utils::parenthetical_split(replace, ',');
2178  }
2179  } else if(apply_to == "new_advancement") {
2180  const std::string& types = effect["types"];
2181  const bool replace = effect["replace"].to_bool(false);
2183 
2184  if(!types.empty()) {
2185  if(replace) {
2187  } else {
2188  std::vector<std::string> temp_advances = utils::parenthetical_split(types, ',');
2189  std::copy(temp_advances.begin(), temp_advances.end(), std::back_inserter(advances_to_));
2190  }
2191  }
2192 
2193  if(effect.has_child("advancement")) {
2194  if(replace) {
2195  advancements_.clear();
2196  }
2197 
2198  config temp = effect;
2199  boost::copy(effect.child_range("advancement"), boost::make_function_output_iterator(ptr_vector_pushback(advancements_)));
2200  }
2201  } else if(apply_to == "remove_advancement") {
2202  const std::string& types = effect["types"];
2203  const std::string& amlas = effect["amlas"];
2205 
2206  std::vector<std::string> temp_advances = utils::parenthetical_split(types, ',');
2208  for(const std::string& unit : temp_advances) {
2209  iter = std::find(advances_to_.begin(), advances_to_.end(), unit);
2210  if(iter != advances_to_.end()) {
2211  advances_to_.erase(iter);
2212  }
2213  }
2214 
2215  temp_advances = utils::parenthetical_split(amlas, ',');
2216 
2217  for(int i = advancements_.size() - 1; i >= 0; i--) {
2218  if(std::find(temp_advances.begin(), temp_advances.end(), advancements_[i]["id"]) != temp_advances.end()) {
2219  advancements_.erase(advancements_.begin() + i);
2220  }
2221  }
2222  } else if(apply_to == "alignment") {
2223  unit_type::ALIGNMENT new_align;
2224  if(new_align.parse(effect["set"])) {
2225  set_alignment(new_align);
2226  }
2227  } else if(apply_to == "max_attacks") {
2228  const std::string& increase = effect["increase"];
2229 
2230  if(!increase.empty()) {
2232  }
2233  } else if(apply_to == "recall_cost") {
2234  const std::string& increase = effect["increase"];
2235  const std::string& set = effect["set"];
2236  const int recall_cost = recall_cost_ < 0 ? resources::gameboard->teams().at(side_).recall_cost() : recall_cost_;
2237 
2238  if(!set.empty()) {
2239  if(set.back() == '%') {
2240  recall_cost_ = lexical_cast_default<int>(set)*recall_cost/100;
2241  } else {
2242  recall_cost_ = lexical_cast_default<int>(set);
2243  }
2244  }
2245 
2246  if(!increase.empty()) {
2247  recall_cost_ = utils::apply_modifier(recall_cost, increase, 1);
2248  }
2249  } else if(effect["apply_to"] == "variation") {
2250  variation_ = effect["name"].str();
2251  const unit_type* base_type = unit_types.find(type().base_id());
2252  assert(base_type != nullptr);
2253  advance_to(*base_type);
2254  if(effect["heal_full"].to_bool(false)) {
2255  heal_fully();
2256  }
2257  } else if(effect["apply_to"] == "type") {
2258  std::string prev_type = effect["prev_type"];
2259  if(prev_type.empty()) {
2260  prev_type = type().base_id();
2261  }
2262  const std::string& new_type_id = effect["name"];
2263  const unit_type* new_type = unit_types.find(new_type_id);
2264  if(new_type) {
2265  const bool heal_full = effect["heal_full"].to_bool(false);
2266  advance_to(*new_type);
2267  preferences::encountered_units().insert(new_type_id);
2268  if(heal_full) {
2269  heal_fully();
2270  }
2271  } else {
2272  WRN_UT << "unknown type= in [effect]apply_to=type, ignoring" << std::endl;
2273  }
2274  }
2275 }
2276 
2277 void unit::add_modification(const std::string& mod_type, const config& mod, bool no_add)
2278 {
2279  bool generate_description = mod["generate_description"].to_bool(true);
2280 
2281  if(no_add == false) {
2282  modifications_.add_child(mod_type, mod);
2283  }
2284 
2285  bool set_poisoned = false; // Tracks if the poisoned state was set after the type or variation was changed.
2286  config type_effect, variation_effect;
2287  std::vector<t_string> effects_description;
2288  for(const config& effect : mod.child_range("effect")) {
2289  // Apply SUF.
2290  if(const config& afilter = effect.child("filter")) {
2291  assert(resources::filter_con);
2292  if(!unit_filter(vconfig(afilter)).matches(*this, loc_)) {
2293  continue;
2294  }
2295  }
2296  const std::string& apply_to = effect["apply_to"];
2297  int times = effect["times"].to_int(1);
2298  t_string description;
2299 
2300  if(effect["times"] == "per level") {
2301  times = level_;
2302  }
2303 
2304  if(times) {
2305  while (times > 0) {
2306  times --;
2307 
2308  bool was_poisoned = get_state(STATE_POISONED);
2309  // Apply unit type/variation changes last to avoid double applying effects on advance.
2310  if(apply_to == "type") {
2311  set_poisoned = false;
2312  type_effect = effect;
2313  continue;
2314  }
2315  if(apply_to == "variation") {
2316  set_poisoned = false;
2317  variation_effect = effect;
2318  continue;
2319  }
2320 
2321  std::string description_component;
2322  if(resources::lua_kernel) {
2323  description_component = resources::lua_kernel->apply_effect(apply_to, *this, effect, true);
2324  } else if(builtin_effects.count(apply_to)) {
2325  // Normally, the built-in effects are dispatched through Lua so that a user
2326  // can override them if desired. However, since they're built-in, we can still
2327  // apply them if the lua kernel is unavailable.
2328  apply_builtin_effect(apply_to, effect);
2329  description_component = describe_builtin_effect(apply_to, effect);
2330  }
2331  if(!times) {
2332  description += description_component;
2333  }
2334  if(!was_poisoned && get_state(STATE_POISONED)) {
2335  set_poisoned = true;
2336  } else if(was_poisoned && !get_state(STATE_POISONED)) {
2337  set_poisoned = false;
2338  }
2339  } // end while
2340  } else { // for times = per level & level = 0 we still need to rebuild the descriptions
2341  if(resources::lua_kernel) {
2342  description += resources::lua_kernel->apply_effect(apply_to, *this, effect, false);
2343  } else if(builtin_effects.count(apply_to)) {
2344  description += describe_builtin_effect(apply_to, effect);
2345  }
2346  }
2347 
2348  if(effect["times"] == "per level" && !times) {
2349  description = VGETTEXT("$effect_description per level", {{"effect_description", description}});
2350  }
2351 
2352  if(!description.empty()) {
2353  effects_description.push_back(description);
2354  }
2355  }
2356  // Apply variations -- only apply if we are adding this for the first time.
2357  if((!type_effect.empty() || !variation_effect.empty()) && no_add == false) {
2358  if(!type_effect.empty()) {
2359  std::string description;
2360  if(resources::lua_kernel) {
2361  description = resources::lua_kernel->apply_effect(type_effect["apply_to"], *this, type_effect, true);
2362  } else if(builtin_effects.count(type_effect["apply_to"])) {
2363  apply_builtin_effect(type_effect["apply_to"], type_effect);
2364  description = describe_builtin_effect(type_effect["apply_to"], type_effect);
2365  }
2366  effects_description.push_back(description);
2367  }
2368  if(!variation_effect.empty()) {
2369  std::string description;
2370  if(resources::lua_kernel) {
2371  description = resources::lua_kernel->apply_effect(variation_effect["apply_to"], *this, variation_effect, true);
2372  } else if(builtin_effects.count(variation_effect["apply_to"])) {
2373  apply_builtin_effect(variation_effect["apply_to"], variation_effect);
2374  description = describe_builtin_effect(variation_effect["apply_to"], variation_effect);
2375  }
2376  effects_description.push_back(description);
2377  }
2378  if(set_poisoned)
2379  // An effect explicitly set the poisoned state, and this
2380  // should override the unit being immune to poison.
2381  set_state(STATE_POISONED, true);
2382  }
2383 
2384  t_string description;
2385 
2386  const t_string& mod_description = mod["description"];
2387  if(!mod_description.empty()) {
2388  description = mod_description;
2389  }
2390 
2391  // Punctuation should be translatable: not all languages use Latin punctuation.
2392  // (However, there maybe is a better way to do it)
2393  if(generate_description && !effects_description.empty()) {
2394  if(!mod_description.empty()) {
2395  description += "\n";
2396  }
2397 
2398  for(const auto& desc_line : effects_description) {
2399  description += desc_line + "\n";
2400  }
2401  }
2402 
2403  // store trait info
2404  if(mod_type == "trait") {
2405  add_trait_description(mod, description);
2406  }
2407 
2408  //NOTE: if not a trait, description is currently not used
2409 }
2410 
2411 void unit::add_trait_description(const config& trait, const t_string& description)
2412 {
2413  const std::string& gender_string = gender_ == unit_race::FEMALE ? "female_name" : "male_name";
2414  const auto& gender_specific_name = trait[gender_string];
2415 
2416  const t_string name = gender_specific_name.empty() ? trait["name"] : gender_specific_name;
2417 
2418  if(!name.empty()) {
2419  trait_names_.push_back(name);
2420  trait_descriptions_.push_back(description);
2421  }
2422 }
2423 
2424 std::string unit::absolute_image() const
2425 {
2426  return type().icon().empty() ? type().image() : type().icon();
2427 }
2428 
2429 std::string unit::default_anim_image() const
2430 {
2431  return type().image().empty() ? type().icon() : type().image();
2432 }
2433 
2435 {
2436  log_scope("apply mods");
2437 
2438  variables_.clear_children("mods");
2439 
2440  for(const auto& mod : ModificationTypes) {
2441  if(mod == "advance" && modifications_.has_child(mod)) {
2442  deprecated_message("[advance]", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use [advancement] instead.");
2443  }
2444 
2445  for(const config& m : modifications_.child_range(mod)) {
2446  lg::scope_logger inner_scope_logging_object__(lg::general(), "add mod");
2447  add_modification(mod, m, true);
2448  }
2449  }
2450 }
2451 
2452 bool unit::invisible(const map_location& loc, bool see_all) const
2453 {
2454  if(loc != get_location()) {
2455  DBG_UT << "unit::invisible called: id = " << id() << " loc = " << loc << " get_loc = " << get_location() << std::endl;
2456  }
2457 
2458  // This is a quick condition to check, and it does not depend on the
2459  // location (so might as well bypass the location-based cache).
2460  if(get_state(STATE_UNCOVERED)) {
2461  return false;
2462  }
2463 
2464  // Fetch from cache
2465  /**
2466  * @todo FIXME: We use the cache only when using the default see_all=true
2467  * Maybe add a second cache if the see_all=false become more frequent.
2468  */
2469  if(see_all) {
2470  const auto itor = invisibility_cache_.find(loc);
2471  if(itor != invisibility_cache_.end()) {
2472  return itor->second;
2473  }
2474  }
2475 
2476  // Test hidden status
2477  static const std::string hides("hides");
2478  bool is_inv = get_ability_bool(hides, loc);
2479  if(is_inv){
2480  is_inv = (resources::gameboard ? !resources::gameboard->would_be_discovered(loc, side_,see_all) : true);
2481  }
2482 
2483  if(see_all) {
2484  // Add to caches
2485  if(invisibility_cache_.empty()) {
2486  units_with_cache.push_back(this);
2487  }
2488 
2489  invisibility_cache_[loc] = is_inv;
2490  }
2491 
2492  return is_inv;
2493 }
2494 
2495 bool unit::is_visible_to_team(const team& team, bool const see_all) const
2496 {
2497  const map_location& loc = get_location();
2498  return is_visible_to_team(loc, team, see_all);
2499 }
2500 
2501 bool unit::is_visible_to_team(const map_location& loc, const team& team, bool const see_all) const
2502 {
2503  if(!display::get_singleton()->get_map().on_board(loc)) {
2504  return false;
2505  }
2506 
2507  if(see_all) {
2508  return true;
2509  }
2510 
2511  if(team.is_enemy(side()) && invisible(loc)) {
2512  return false;
2513  }
2514 
2515  // allied planned moves are also visible under fog. (we assume that fake units on the map are always whiteboard markers)
2516  if(!team.is_enemy(side()) && underlying_id_.is_fake()) {
2517  return true;
2518  }
2519 
2520  // when the whiteboard planned unit map is applied, it uses moved the _real_ unit so
2521  // underlying_id_.is_fake() will be false and the check above will not apply.
2522  // TODO: improve this check so that is also works for allied planned units but without
2523  // breaking sp campaigns with allies under fog. We probably need an explicit flag
2524  // is_planned_ in unit that is set by the whiteboard.
2525  if(team.side() == side()) {
2526  return true;
2527  }
2528 
2529  if(team.fogged(loc)) {
2530  return false;
2531  }
2532 
2533  return true;
2534 }
2535 
2537 {
2538  if(underlying_id_.value == 0) {
2540  underlying_id_ = id_manager.next_id();
2541  } else {
2542  underlying_id_ = id_manager.next_fake_id();
2543  }
2544  }
2545 
2546  if(id_.empty() /*&& !underlying_id_.is_fake()*/) {
2547  std::stringstream ss;
2548  ss << (type_id().empty() ? "Unit" : type_id()) << "-" << underlying_id_.value;
2549  id_ = ss.str();
2550  }
2551 }
2552 
2553 unit& unit::mark_clone(bool is_temporary)
2554 {
2556  if(is_temporary) {
2557  underlying_id_ = ids.next_fake_id();
2558  } else {
2560  underlying_id_ = ids.next_id();
2561  }
2562  else {
2563  underlying_id_ = ids.next_fake_id();
2564  }
2565  std::string::size_type pos = id_.find_last_of('-');
2566  if(pos != std::string::npos && pos+1 < id_.size()
2567  && id_.find_first_not_of("0123456789", pos+1) == std::string::npos) {
2568  // this appears to be a duplicate of a generic unit, so give it a new id
2569  WRN_UT << "assigning new id to clone of generic unit " << id_ << std::endl;
2570  id_.clear();
2571  set_underlying_id(ids);
2572  }
2573  }
2574  return *this;
2575 }
2576 
2577 
2579  : u_(const_cast<unit&>(u))
2580  , moves_(u.movement_left(true))
2581 {
2582  if(operate) {
2584  }
2585 }
2586 
2588 {
2589  assert(resources::gameboard);
2590  try {
2591  if(!resources::gameboard->units().has_unit(&u_)) {
2592  /*
2593  * It might be valid that the unit is not in the unit map.
2594  * It might also mean a no longer valid unit will be assigned to.
2595  */
2596  DBG_UT << "The unit to be removed is not in the unit map." << std::endl;
2597  }
2598 
2600  } catch(...) {}
2601 }
2602 
2603 std::string unit::TC_image_mods() const
2604 {
2605  return formatter() << "~RC(" << flag_rgb() << ">" << team::get_side_color_id(side()) << ")";
2606 }
2607 
2608 std::string unit::image_mods() const
2609 {
2610  if(!image_mods_.empty()) {
2611  return formatter() << "~" << image_mods_ << TC_image_mods();
2612  }
2613 
2614  return TC_image_mods();
2615 }
2616 
2617 // Called by the Lua API after resetting an attack pointer.
2619 {
2620  set_attr_changed(UA_ATTACKS);
2621  auto iter = std::find(attacks_.begin(), attacks_.end(), atk);
2622  if(iter == attacks_.end()) {
2623  return false;
2624  }
2625  attacks_.erase(iter);
2626  return true;
2627 }
2628 
2630 {
2631  if(attacks_left_ == max_attacks_) {
2632  //TODO: add state_not_attacked
2633  }
2634 
2635  set_attacks(0);
2636 }
2637 
2639 {
2640  if(movement_left() == total_movement()) {
2641  set_state(STATE_NOT_MOVED,true);
2642  }
2643 
2644  set_movement(0, true);
2645 }
2646 
2647 void unit::set_hidden(bool state) const
2648 {
2649 // appearance_changed_ = true;
2650  hidden_ = state;
2651  if(!state) {
2652  return;
2653  }
2654 
2655  // We need to get rid of haloes immediately to avoid display glitches
2656  anim_comp_->clear_haloes();
2657 }
2658 
2659 void unit::set_image_halo(const std::string& halo)
2660 {
2661  appearance_changed_ = true;
2662  anim_comp_->clear_haloes();
2663  halo_.reset(new std::string(halo));
2664 }
2665 
2667 {
2668  if(upkeep.empty()) {
2669  return;
2670  }
2671 
2672  try {
2673  upkeep_ = upkeep.apply_visitor(upkeep_parser_visitor());
2674  } catch(std::invalid_argument& e) {
2675  WRN_UT << "Found invalid upkeep=\"" << e.what() << "\" in a unit" << std::endl;
2676  upkeep_ = upkeep_full();
2677  }
2678 }
2679 
2681 {
2682  upkeep = boost::apply_visitor(upkeep_type_visitor(), upkeep_);
2683 }
2684 
2686 {
2687  changed_attributes_.reset();
2688  for(const auto& a_ptr : attacks_) {
2689  a_ptr->set_changed(false);
2690  }
2691 }
2692 
2693 // Filters unimportant stats from the unit config and returns a checksum of
2694 // the remaining config.
2695 std::string get_checksum(const unit& u)
2696 {
2697  config unit_config;
2698  config wcfg;
2699  u.write(unit_config);
2700 
2701  const std::array<std::string, 22> main_keys {{
2702  "advances_to",
2703  "alignment",
2704  "cost",
2705  "experience",
2706  "gender",
2707  "hitpoints",
2708  "ignore_race_traits",
2709  "ignore_global_traits",
2710  "level",
2711  "recall_cost",
2712  "max_attacks",
2713  "max_experience",
2714  "max_hitpoints",
2715  "max_moves",
2716  "movement",
2717  "movement_type",
2718  "race",
2719  "random_traits",
2720  "resting",
2721  "undead_variation",
2722  "upkeep",
2723  "zoc"
2724  }};
2725 
2726  for(const std::string& main_key : main_keys) {
2727  wcfg[main_key] = unit_config[main_key];
2728  }
2729 
2730  const std::array<std::string, 5> attack_keys {{
2731  "name",
2732  "type",
2733  "range",
2734  "damage",
2735  "number"
2736  }};
2737 
2738  for(const config& att : unit_config.child_range("attack")) {
2739  config& child = wcfg.add_child("attack");
2740 
2741  for(const std::string& attack_key : attack_keys) {
2742  child[attack_key] = att[attack_key];
2743  }
2744 
2745  for(const config& spec : att.child_range("specials")) {
2746  config& child_spec = child.add_child("specials", spec);
2747 
2748  child_spec.recursive_clear_value("description");
2749  }
2750  }
2751 
2752  for(const config& abi : unit_config.child_range("abilities")) {
2753  config& child = wcfg.add_child("abilities", abi);
2754 
2755  child.recursive_clear_value("description");
2756  child.recursive_clear_value("description_inactive");
2757  child.recursive_clear_value("name");
2758  child.recursive_clear_value("name_inactive");
2759  }
2760 
2761  for(const config& trait : unit_config.child_range("trait")) {
2762  config& child = wcfg.add_child("trait", trait);
2763 
2764  child.recursive_clear_value("description");
2765  child.recursive_clear_value("male_name");
2766  child.recursive_clear_value("female_name");
2767  child.recursive_clear_value("name");
2768  }
2769 
2770  const std::array<std::string, 6> child_keys {{
2771  "advance_from",
2772  "defense",
2773  "movement_costs",
2774  "vision_costs",
2775  "jamming_costs",
2776  "resistance"
2777  }};
2778 
2779  for(const std::string& child_key : child_keys) {
2780  for(const config& c : unit_config.child_range(child_key)) {
2781  wcfg.add_child(child_key, c);
2782  }
2783  }
2784 
2785  DBG_UT << wcfg;
2786 
2787  return wcfg.hash();
2788 }
2789 
2790 void swap(unit& lhs, unit& rhs)
2791 {
2792  lhs.swap(rhs);
2793 }
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:267
bool empty() const
Tests for an attribute that either was never set or was set to "".
bool ability_affects_weapon(const config &cfg, const_attack_ptr weapon, bool is_opp) const
filters the weapons that condition the use of abilities for combat ([resistance],[leadership] or abil...
Definition: abilities.cpp:442
void remove()
Removes a tip.
Definition: tooltip.cpp:189
const std::string & base_id() const
The id of the original type from which this (variation) descended.
Definition: types.hpp:136
const unit_type * type_
Never nullptr.
Definition: unit.hpp:1773
attack_list attacks_
Definition: unit.hpp:1841
void set_movement(int moves, bool unit_action=false)
Set this unit&#39;s remaining movement to moves.
Definition: unit.cpp:1220
t_string type_name_
The displayed name of this unit type.
Definition: unit.hpp:1776
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:65
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:420
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:88
std::vector< std::string > recruit_list_
Definition: unit.hpp:1797
void set_big_profile(const std::string &value)
Definition: unit.hpp:583
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:921
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:1383
const unit_type * find(const std::string &key, unit_type::BUILD_STATUS status=unit_type::FULL) const
Finds a unit_type by its id() and makes sure it is built to the specified level.
Definition: types.cpp:1208
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:1867
int recall_cost_
Definition: unit.hpp:1795
utils::string_map modification_descriptions_
Definition: unit.hpp:1857
vconfig child(const std::string &key) const
Returns a child of *this whose key is key.
Definition: variable.cpp:288
std::map< std::string, t_string > string_map
void apply_modifications()
Re-apply all saved modifications.
Definition: unit.cpp:2434
void clear_children(T... keys)
Definition: config.hpp:479
void recursive_clear_value(config_key_type key)
Definition: config.cpp:652
void parse_upkeep(const config::attribute_value &upkeep)
Definition: unit.cpp:2666
The unit is a guardian - it won&#39;t move unless a target is sighted.
Definition: unit.hpp:844
This class represents a single unit of a specific type.
Definition: unit.hpp:106
std::string big_profile() const
An optional profile image displays when this unit is &#39;speaking&#39; via [message].
Definition: unit.cpp:1054
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:165
void append(const config &cfg)
Append data from another config object to this one.
Definition: config.cpp:287
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:922
void new_turn()
Refresh unit for the beginning of a turn.
Definition: unit.cpp:1283
The unit is uncovered - it was hiding but has been spotted.
Definition: unit.hpp:841
std::string image_mods_
Definition: unit.hpp:1801
void set_usage(const std::string &usage)
Sets this unit&#39;s usage.
Definition: unit.hpp:670
std::vector< std::string > advances_to_
Definition: unit.hpp:1770
t_string name_
Definition: unit.hpp:1782
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:229
Variant for storing WML attributes.
std::vector< t_string > trait_names_
Definition: unit.hpp:1849
void write_upkeep(config::attribute_value &upkeep) const
Definition: unit.cpp:2680
bool get_state(const std::string &state) const
Check if the unit is affected by a status effect.
Definition: unit.cpp:1355
int vision_
Definition: unit.hpp:1813
const std::vector< t_string > & special_notes() const
Definition: types.cpp:494
const std::string & big_profile() const
Definition: types.hpp:162
unit_race::GENDER gender() const
The gender of this unit.
Definition: unit.hpp:439
void check_types(const std::vector< std::string > &types) const
Definition: types.cpp:1233
const std::vector< std::string > & advances_to() const
A vector of unit_type ids that this unit_type can advance to.
Definition: types.hpp:106
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.
bool has_attribute(config_key_type key) const
Definition: config.cpp:213
#define a
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:473
config events_
Definition: unit.hpp:1833
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:412
const std::string & flag_rgb() const
Definition: types.cpp:684
unsigned child_count(config_key_type key) const
Definition: config.cpp:390
unit_type::ALIGNMENT alignment_
Definition: unit.hpp:1798
bool is_fearless_
Definition: unit.hpp:1855
void intrusive_ptr_add_ref(const unit *u)
Intrusive Pointer interface.
Definition: unit.cpp:215
map_location::DIRECTION facing_
Definition: unit.hpp:1846
child_itors child_range(config_key_type key)
Definition: config.cpp:362
std::string flag_rgb_
Definition: unit.hpp:1800
config & variables()
Gets any user-defined variables this unit &#39;owns&#39;.
Definition: unit.hpp:681
void set_image_ellipse(const std::string &ellipse)
Set the unit&#39;s ellipse image.
Definition: unit.hpp:1534
void set_small_profile(const std::string &value)
Definition: unit.hpp:570
int jamming_
Definition: unit.hpp:1814
int unit_value_
Definition: unit.hpp:1852
A status effect not known to the engine.
Definition: unit.hpp:845
attribute_map::value_type attribute
Definition: config.hpp:226
void generate_traits(bool must_have_only=false)
Applies mandatory traits (e.g.
Definition: unit.cpp:845
bool generate_name_
Definition: unit.hpp:1880
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:742
std::string unit_rgb
bool hold_position_
Definition: unit.hpp:1818
std::vector< t_string > special_notes_
Definition: unit.hpp:1873
void clear_changed_attributes()
Definition: unit.cpp:2685
int wml_x() const
Definition: location.hpp:157
The unit is poisoned - it loses health each turn.
Definition: unit.hpp:839
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:541
unit_type_data unit_types
Definition: types.cpp:1433
void set_wml_x(int v)
Definition: location.hpp:160
The unit is petrified - it cannot move or be attacked.
Definition: unit.hpp:840
config variables_
Definition: unit.hpp:1832
const config & get_cfg() const
Definition: types.hpp:266
int resistance_against(const attack_type &attack) const
Returns the resistance against the indicated attack.
Definition: movetype.hpp:271
std::string absolute_image() const
The name of the file to game_display (used in menus).
Definition: unit.cpp:2424
#define VNGETTEXT(msgid, msgid_plural, count,...)
const std::string & variation_id() const
The id of this variation; empty if it&#39;s a gender variation or a base unit.
Definition: types.hpp:138
const std::string & type_id() const
The id of this unit&#39;s type.
Definition: unit.hpp:334
void clear()
Definition: config.cpp:863
void remove_attacks_ai()
Set the unit to have no attacks left for this turn.
Definition: unit.cpp:2629
void merge(const config &new_cfg, bool overwrite=true)
Merges the given config over the existing data, the config should have zero or more children named "m...
Definition: movetype.cpp:855
void write(config &cfg) const
Writes the movement type data to the provided config.
Definition: movetype.cpp:899
bool is_healthy_
Definition: unit.hpp:1855
-file sdl_utils.hpp
void set_facing(map_location::DIRECTION dir) const
The this unit&#39;s facing.
Definition: unit.cpp:1625
void set_interrupted_move(const map_location &interrupted_move)
Set the target location of the unit&#39;s interrupted move.
Definition: unit.hpp:1387
static int xp_to_advance(const std::string &s)
Definition: menu.cpp:115
int max_hit_points_
Definition: unit.hpp:1789
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.
void set_total_movement(int value)
Definition: unit.hpp:1234
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:809
std::string small_profile_
Definition: unit.hpp:1885
A single unit type that the player may recruit.
Definition: types.hpp:42
void write(config &cfg, bool write_all=true) const
Serializes the current unit metadata values.
Definition: unit.cpp:1460
game_data * gamedata
Definition: resources.cpp:22
static std::map< std::string, state_t > known_boolean_state_names_
Definition: unit.hpp:1830
map_location goto_
Definition: unit.hpp:1853
bool filter_base_matches(const config &cfg, int def)
Definition: abilities.cpp:1403
std::vector< unit_ability >::iterator iterator
Definition: unit.hpp:69
state_t
Built-in status effects known to the engine.
Definition: unit.hpp:837
map_location loc_
std::unique_ptr< unit_formula_manager > formula_man_
Definition: unit.hpp:1809
void set_level(int level)
Sets the current level of this unit.
Definition: unit.hpp:539
const unit_type & type() const
This unit&#39;s type, accounting for gender and variation.
Definition: unit.hpp:323
color_t hp_color() const
Color for this unit&#39;s current hitpoints.
Definition: unit.cpp:1124
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:515
Pubic entry points for the MP workflow.
Definition: lobby_data.cpp:50
void heal(int amount)
Heal the unit The number of hitpoints to gain.
Definition: unit.cpp:1322
void add_modification(const std::string &type, const config &modification, bool no_add=false)
Add a new modification to the unit.
Definition: unit.cpp:2277
int defense_modifier(const t_translation::terrain_code &terrain) const
The unit&#39;s defense on a given terrain.
Definition: unit.cpp:1649
static void clear_status_caches()
Clear this unit status cache for all units.
Definition: unit.cpp:719
void set_advances_to(const std::vector< std::string > &advances_to)
Sets this unit&#39;s advancement options.
Definition: unit.cpp:1213
const_all_children_iterator ordered_end() const
Definition: config.cpp:911
child_list get_children(const std::string &key) const
Definition: variable.cpp:226
std::string role_
Definition: unit.hpp:1840
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:44
void set_max_attacks(int value)
Definition: unit.hpp:958
#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:1076
const config & get_cfg_for_units() const
Returns a trimmed config suitable for use with units.
Definition: types.hpp:268
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:236
const std::string & id() const
Gets this unit&#39;s id.
Definition: unit.hpp:351
void swap(unit &)
Swap, for copy and swap idiom.
Definition: unit.cpp:772
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:155
void set_state(const std::string &state, bool value)
Set whether the unit is affected by a status effect.
Definition: unit.cpp:1403
int vision() const
Definition: types.hpp:150
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:2536
const movetype & movement_type() const
Definition: types.hpp:171
The unit is slowed - it moves slower and does less damage.
Definition: unit.hpp:838
void set_recruits(const std::vector< std::string > &recruits)
Sets the recruit list.
Definition: unit.cpp:1189
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:129
bool get_attr_changed(UNIT_ATTRIBUTE attr) const
Definition: unit.hpp:155
std::string profile_
Definition: unit.hpp:1884
int max_movement_
Definition: unit.hpp:1812
void new_scenario()
Refresh unit for the beginning of a new scenario.
Definition: unit.cpp:1307
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:1198
const std::string & usage() const
Definition: types.hpp:158
void set_max_experience(int value)
Definition: unit.hpp:508
color_t xp_color() const
Color for this unit&#39;s XP.
Definition: unit.cpp:1178
game_board * gameboard
Definition: resources.cpp:20
std::string ellipse() const
Definition: types.hpp:164
static const std::set< std::string > effects
The set of applicable effects for movement types.
Definition: movetype.hpp:297
#define WRN_UT
Definition: unit.cpp:80
bool appearance_changed_
Definition: unit.hpp:1888
const t_string & name() const
Gets this unit&#39;s translatable display name.
Definition: unit.hpp:374
unit_race::GENDER string_gender(const std::string &str, unit_race::GENDER def)
Definition: race.cpp:141
int upkeep() const
Gets the amount of gold this unit costs a side per turn.
Definition: unit.cpp:1634
int kill_experience
Definition: game_config.cpp:57
std::vector< std::string > advances_to_t
Definition: unit.hpp:205
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:1791
std::size_t value
Definition: id.hpp:26
void set_alignment(unit_type::ALIGNMENT alignment)
Sets the alignment of this unit.
Definition: unit.hpp:455
bool get_attacks_changed() const
Definition: unit.cpp:1450
const std::string & id() const
The id for this unit_type.
Definition: types.hpp:132
void set_hidden(bool state) const
Sets whether the unit is hidden on the map.
Definition: unit.cpp:2647
map_display and display: classes which take care of displaying the map and game-data on the screen...
std::string default_anim_image() const
The default image to use for animation frames with no defined image.
Definition: unit.cpp:2429
const std::vector< std::string > & overlays() const
Get the unit&#39;s overlay images.
Definition: unit.hpp:1562
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:1063
The unit has not moved.
Definition: unit.hpp:842
void set_advancements(std::vector< config > advancements)
Sets the raw modification advancement option data.
Definition: unit.cpp:1834
bool mod_duration_match(const std::string &mod_dur, const std::string &goal_dur)
Determines if mod_dur "matches" goal_dur.
Definition: unit.cpp:1236
std::bitset< UA_COUNT > changed_attributes_
Definition: unit.hpp:1889
unit_race::GENDER gender_
Definition: unit.hpp:1807
static color_t hp_color_max()
Definition: unit.cpp:1134
int hit_points_
Definition: unit.hpp:1788
static const ::config * terrain
The terrain used to create the cache.
Definition: minimap.cpp:130
std::unique_ptr< std::string > ellipse_
Definition: unit.hpp:1877
game_events::manager * game_events
Definition: resources.cpp:24
bool random_traits_
Definition: unit.hpp:1879
all_children_iterator erase(const all_children_iterator &i)
Definition: config.cpp:689
void expire_modifications(const std::string &duration)
Clears those modifications whose duration has expired.
Definition: unit.cpp:1246
std::size_t modification_count(const std::string &type, const std::string &id) const
Count modifications of a particular type.
Definition: unit.cpp:1844
void set_attr_changed(UNIT_ATTRIBUTE attr)
Definition: unit.hpp:150
log_domain & general()
Definition: log.cpp:104
const std::string & gender_string(unit_race::GENDER gender)
Definition: race.cpp:131
std::string flag_rgb
static std::string get_side_color_id(unsigned side)
Definition: team.cpp:961
double xp_bar_scaling() const
Definition: types.hpp:146
unit & mark_clone(bool is_temporary)
Mark this unit as clone so it can be inserted to unit_map.
Definition: unit.cpp:2553
bool is_fake() const
Definition: id.hpp:28
bool loyal() const
Gets whether this unit is loyal - ie, it costs no upkeep.
Definition: unit.cpp:1644
config abilities_
Definition: unit.hpp:1868
std::vector< std::string > overlays_
Definition: unit.hpp:1838
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:1864
bool invisible(const map_location &loc, bool see_all=true) const
Definition: unit.cpp:2452
const advancements_list & modification_advancements() const
The raw, unparsed data for modification advancements.
Definition: unit.hpp:291
const std::string & undead_variation() const
Info on the type of unit that the unit reanimates as.
Definition: types.hpp:124
#define DBG_UT
Definition: unit.cpp:78
movetype movement_type_
Definition: unit.hpp:1816
const std::string log_id() const
A variant on id() that is more descriptive, for use with message logging.
Definition: types.hpp:134
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:144
config filter_recall_
Definition: unit.hpp:1834
const unit_race * find_race(const std::string &) const
Definition: types.cpp:1320
void remove_ability_by_id(const std::string &ability)
Removes a unit&#39;s abilities with a specific ID.
Definition: unit.cpp:1437
bool has_zoc() const
Definition: types.hpp:215
void set_image_halo(const std::string &halo)
Set the unit&#39;s halo image.
Definition: unit.cpp:2659
void generate_name()
Generates a random race-appropriate name if one has not already been provided.
Definition: unit.cpp:836
int max_attacks_
Definition: unit.hpp:1823
void swap(unit &lhs, unit &rhs)
Implement non-member swap function for std::swap (calls unit::swap).
Definition: unit.cpp:2790
std::size_t i
Definition: function.cpp:933
int recall_cost() const
Definition: types.hpp:148
void set_undead_variation(const std::string &value)
The ID of the undead variation (ie, dwarf, swimmer) of this unit.
Definition: unit.hpp:552
int max_hitpoints() const
The max number of hitpoints this unit can have.
Definition: unit.hpp:479
Visitor helper class to fetch the appropriate upkeep value.
Definition: unit.hpp:1110
std::string get_checksum(const unit &u)
Gets a checksum for a unit.
Definition: unit.cpp:2695
double hp_bar_scaling_
Definition: unit.hpp:1865
static map_location::DIRECTION s
map_location interrupted_move_
Definition: unit.hpp:1853
const config & abilities_cfg() const
Definition: types.hpp:223
void set_emit_zoc(bool val)
Sets the raw zone-of-control flag.
Definition: unit.hpp:1313
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:2411
bool can_recruit() const
Whether this unit can recruit other units - ie, are they a leader unit.
Definition: unit.hpp:590
iterator begin()
Definition: unit.hpp:72
bool canrecruit_
Definition: unit.hpp:1796
std::map< std::string, std::string > advancement_icons() const
Gets and image path and and associated description for each advancement option.
Definition: unit.cpp:1717
int experience_
Definition: unit.hpp:1790
std::unique_ptr< std::string > usage_
Definition: unit.hpp:1875
#define log_scope(description)
Definition: log.hpp:186
std::string halo() const
Definition: types.hpp:163
n_unit::unit_id underlying_id_
Definition: unit.hpp:1783
double xp_bar_scaling_
Definition: unit.hpp:1865
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:160
void validate_side(int side)
Definition: team.cpp:759
std::vector< std::string > get_traits_list() const
Gets a list of the traits this unit currently has.
Definition: unit.cpp:902
int level() const
Definition: types.hpp:147
t_string description_
Definition: unit.hpp:1872
std::set< std::string > & encountered_units()
Definition: game.cpp:954
int get_random_int(int min, int max)
This helper method provides a random int from the underlying generator, using results of next_random...
Definition: random.hpp:51
int attacks_left_
Definition: unit.hpp:1822
void heal_fully()
Fully heal the unit, restoring it to max hitpoints.
Definition: unit.hpp:809
void set_max_hitpoints(int value)
Definition: unit.hpp:484
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:161
int hitpoints() const
Definition: types.hpp:144
The unit cannot be healed.
Definition: unit.hpp:843
int jamming() const
Definition: types.hpp:153
std::unique_ptr< std::string > halo_
Definition: unit.hpp:1876
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
int movement() const
Definition: types.hpp:149
std::shared_ptr< attack_type > attack_ptr
Definition: ptr.hpp:36
config & add_child(config_key_type key)
Definition: config.cpp:476
bool is_visible_to_team(const team &team, bool const see_all=true) const
Definition: unit.cpp:2495
advancements_list advancements_
Definition: unit.hpp:1870
Handling of system events.
Definition: manager.hpp:42
const std::vector< std::string > & recruits() const
The type IDs of the other units this unit may recruit, if possible.
Definition: unit.hpp:602
const std::string & flag_rgb() const
Get the source color palette to use when recoloring the unit&#39;s image.
Definition: unit.cpp:1081
long ref_count_
Definition: unit.hpp:1765
const_all_children_iterator ordered_begin() const
Definition: config.cpp:901
std::unique_ptr< unit_animation_component > anim_comp_
Definition: unit.hpp:1862
static std::string type()
Definition: unit.hpp:1106
config::const_child_itors possible_traits() const
Definition: types.hpp:220
const std::string & image() const
Definition: types.hpp:159
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:455
unsigned int num_traits() const
Definition: types.hpp:126
int movement_
Definition: unit.hpp:1811
static const std::set< std::string > builtin_effects
Definition: unit.hpp:1480
n_unit::id_manager & unit_id_manager()
Definition: game_board.hpp:86
double t
Definition: astarsearch.cpp:64
const unit_type & get_variation(const std::string &id) const
Definition: types.cpp:470
upkeep_t upkeep_
Definition: unit.hpp:1882
bool find(E event, F functor)
Tests whether an event handler is available.
int apply_modifier(const int number, const std::string &amount, const int minimum)
bool unrenamable_
Definition: unit.hpp:1803
int level_
Definition: unit.hpp:1793
std::vector< config > get_modification_advances() const
Gets any non-typed advanced options set by modifications.
Definition: unit.cpp:1774
int max_attacks() const
Definition: types.hpp:154
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1320
std::bitset< num_bool_states > known_boolean_states_
Definition: unit.hpp:1829
A variable-expanding proxy for the config class.
Definition: variable.hpp:44
const unit_race * race() const
Never returns nullptr, but may point to the null race.
Definition: types.hpp:262
this module manages the cache of images.
const config & get_config() const
Definition: variable.hpp:82
Standard logging facilities (interface).
bool can_advance() const
Checks whether this unit has any options to advance to.
Definition: unit.hpp:239
const unit_race * race_
Never nullptr, but may point to the null race.
Definition: unit.hpp:1779
void apply_builtin_effect(std::string type, const config &effect)
Apply a builtin effect to the unit.
Definition: unit.cpp:1935
std::string variation_
Definition: unit.hpp:1786
V::result_type apply_visitor(const V &visitor) const
Applies a visitor to the underlying variant.
t_string unit_description() const
A detailed description of this unit.
Definition: unit.hpp:421
const unit_type & get_gender_unit_type(std::string gender) const
Returns a gendered variant of this unit_type.
Definition: types.cpp:449
static void check_id(std::string &id)
Validate the id argument.
Definition: types.cpp:1407
bool emit_zoc_
Definition: unit.hpp:1836
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:1870
std::map< map_location, bool > invisibility_cache_
Hold the visibility status cache for a unit, when not uncovered.
Definition: unit.hpp:1898
double hp_bar_scaling() const
Definition: types.hpp:145
int total_movement() const
The maximum moves this unit has.
Definition: unit.hpp:1229
const map_location goto_
Definition: move.cpp:309
bool fogged(const map_location &loc) const
Definition: team.cpp:662
std::string id_
Definition: unit.hpp:1781
#define e
int side() const
The side this unit belongs to.
Definition: unit.hpp:311
std::vector< t_string > trait_descriptions_
Definition: unit.hpp:1850
void end_turn()
Refresh unit for the end of a turn.
Definition: unit.cpp:1293
boost::ptr_vector< config > * vec_
Definition: unit.cpp:294
static color_t hp_color_impl(int hitpoints, int max_hitpoints)
Definition: unit.cpp:1086
bool resting_
Definition: unit.hpp:1820
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:453
unit_ability_list get_abilities(const std::string &tag_name, const map_location &loc) const
Gets the unit&#39;s active abilities of a particular type if it were on a specified location.
Definition: abilities.cpp:184
const_attack_itors attacks() const
Definition: types.cpp:507
Visitor helper class to parse the upkeep value from a config.
Definition: unit.hpp:1156
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:1692
std::vector< vconfig > child_list
Definition: variable.hpp:85
std::vector< std::pair< std::string, std::string > > amla_icons() const
Gets the image and description data for modification advancements.
Definition: unit.cpp:1757
int side() const
Definition: team.hpp:188
t_string unit_description() const
Definition: types.cpp:480
#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:1137
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:80
map_location loc_
Definition: unit.hpp:1768
mock_char c
bool resistance_filter_matches(const config &cfg, bool attacker, const std::string &damage_name, int res) const
Definition: unit.cpp:1664
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:2603
void remove_movement_ai()
Sets the unit to have no moves left for this turn.
Definition: unit.cpp:2638
const std::set< std::string > get_states() const
Get the status effects currently affecting the unit.
Definition: unit.cpp:1338
const advances_to_t & advances_to() const
Gets the possible types this unit can advance to on level-up.
Definition: unit.hpp:211
virtual ~unit()
Definition: unit.cpp:753
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, or -1 if the side&#39;s default recall cost is used...
Definition: unit.hpp:618
unit()
Definition: unit.cpp:379
static std::string write_direction(DIRECTION dir)
Definition: location.cpp:140
void remove_child(config_key_type key, unsigned index)
Definition: config.cpp:694
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:1335
void add_events(const config::const_child_itors &cfgs, const std::string &type=std::string())
Definition: manager.cpp:115
int side_
Definition: unit.hpp:1805
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:1245
std::size_t underlying_id() const
This unit&#39;s unique internal ID.
Definition: unit.hpp:363
bool empty() const
Definition: config.cpp:884
std::string image_mods() const
Gets an IPF string containing all IPF image mods.
Definition: unit.cpp:2608
bool has_ability_by_id(const std::string &ability) const
Check if the unit has an ability of a specific ID.
Definition: unit.cpp:1426
iterator end()
Definition: unit.hpp:74
config::const_child_itors advancements() const
Definition: types.hpp:226
std::string generate_name(GENDER gender) const
Definition: race.cpp:103
bool end_turn_
Definition: unit.hpp:1819
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:1825
const std::string & default_variation() const
Definition: types.hpp:156
std::pair< std::string, unsigned > item
Definition: help_impl.hpp:371
std::string undead_variation_
Definition: unit.hpp:1785
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:2618