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