The Battle for Wesnoth  1.17.21+dev
unit.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2023
3  by David White <dave@whitevine.net>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
16 /**
17  * @file
18  * Routines to manage units.
19  */
20 
21 #include "units/unit.hpp"
22 
23 #include "ai/manager.hpp"
24 #include "color.hpp"
25 #include "deprecation.hpp"
26 #include "display.hpp"
27 #include "formatter.hpp"
28 #include "formula/string_utils.hpp" // for VGETTEXT
29 #include "game_board.hpp" // for game_board
30 #include "game_config.hpp" // for add_color_info, etc
31 #include "game_data.hpp"
32 #include "game_errors.hpp" // for game_error
33 #include "game_events/manager.hpp" // for add_events
34 #include "game_version.hpp"
35 #include "gettext.hpp" // for N_
36 #include "lexical_cast.hpp"
37 #include "log.hpp" // for LOG_STREAM, logger, etc
38 #include "map/map.hpp" // for gamemap
39 #include "preferences/game.hpp" // for encountered_units
40 #include "random.hpp" // for generator, rng
41 #include "resources.hpp" // for units, gameboard, teams, etc
42 #include "scripting/game_lua_kernel.hpp" // for game_lua_kernel
43 #include "side_filter.hpp" // for side_filter
44 #include "synced_context.hpp"
45 #include "team.hpp" // for team, get_teams, etc
46 #include "terrain/filter.hpp" // for terrain_filter
47 #include "units/abilities.hpp" // for effect, filter_base_matches
48 #include "units/animation.hpp" // for unit_animation
49 #include "units/animation_component.hpp" // for unit_animation_component
50 #include "units/filter.hpp"
51 #include "units/formula_manager.hpp" // for unit_formula_manager
52 #include "units/id.hpp"
53 #include "units/map.hpp" // for unit_map, etc
54 #include "units/types.hpp"
55 #include "utils/config_filters.hpp"
56 #include "variable.hpp" // for vconfig, etc
57 
58 #include <cassert> // for assert
59 #include <cstdlib> // for rand
60 #include <exception> // for exception
61 #include <functional>
62 #include <iterator> // for back_insert_iterator, etc
63 #include <new> // for operator new
64 #include <ostream> // for operator<<, basic_ostream, etc
65 #include <string_view>
66 
67 namespace t_translation { struct terrain_code; }
68 
69 static lg::log_domain log_unit("unit");
70 #define DBG_UT LOG_STREAM(debug, log_unit)
71 #define LOG_UT LOG_STREAM(info, log_unit)
72 #define WRN_UT LOG_STREAM(warn, log_unit)
73 #define ERR_UT LOG_STREAM(err, log_unit)
74 
75 namespace
76 {
77  // "advance" only kept around for backwards compatibility; only "advancement" should be used
78  const std::set<std::string_view> ModificationTypes { "advancement", "advance", "trait", "object" };
79 
80  /**
81  * Pointers to units which have data in their internal caches. The
82  * destructor of an unit removes itself from the cache, so the pointers are
83  * always valid.
84  */
85  static std::vector<const unit*> units_with_cache;
86 
87  static const std::string leader_crown_path = "misc/leader-crown.png";
88  static const std::set<std::string_view> internalized_attrs {
89  "type",
90  "id",
91  "name",
92  "male_name",
93  "female_name",
94  "gender",
95  "random_gender",
96  "variation",
97  "role",
98  "ai_special",
99  "side",
100  "underlying_id",
101  "overlays",
102  "facing",
103  "race",
104  "level",
105  "recall_cost",
106  "undead_variation",
107  "max_attacks",
108  "attacks_left",
109  "alpha",
110  "zoc",
111  "flying",
112  "cost",
113  "max_hitpoints",
114  "max_moves",
115  "vision",
116  "jamming",
117  "max_experience",
118  "advances_to",
119  "hitpoints",
120  "goto_x",
121  "goto_y",
122  "moves",
123  "experience",
124  "resting",
125  "unrenamable",
126  "alignment",
127  "canrecruit",
128  "extra_recruit",
129  "x",
130  "y",
131  "placement",
132  "parent_type",
133  "description",
134  "usage",
135  "halo",
136  "ellipse",
137  "upkeep",
138  "random_traits",
139  "generate_name",
140  "profile",
141  "small_profile",
142  "fire_event",
143  "passable",
144  "overwrite",
145  "location_id",
146  "hidden",
147  // Useless attributes created when saving units to WML:
148  "flag_rgb",
149  "language_name",
150  "image",
151  "image_icon"
152  };
153 
154  void warn_unknown_attribute(const config::const_attr_itors& cfg)
155  {
156  config::const_attribute_iterator cur = cfg.begin();
157  config::const_attribute_iterator end = cfg.end();
158 
159  auto cur_known = internalized_attrs.begin();
160  auto end_known = internalized_attrs.end();
161 
162  while(cur_known != end_known) {
163  if(cur == end) {
164  return;
165  }
166  int comp = cur->first.compare(*cur_known);
167  if(comp < 0) {
168  WRN_UT << "Unknown attribute '" << cur->first << "' discarded.";
169  ++cur;
170  }
171  else if(comp == 0) {
172  ++cur;
173  ++cur_known;
174  }
175  else {
176  ++cur_known;
177  }
178  }
179 
180  while(cur != end) {
181  WRN_UT << "Unknown attribute '" << cur->first << "' discarded.";
182  ++cur;
183  }
184  }
185 } // end anon namespace
186 
187 /**
188  * Converts a string ID to a unit_type.
189  * Throws a game_error exception if the string does not correspond to a type.
190  */
191 static const unit_type& get_unit_type(const std::string& type_id)
192 {
193  if(type_id.empty()) {
194  throw unit_type::error("creating unit with an empty type field");
195  }
196  std::string new_id = type_id;
197  unit_type::check_id(new_id);
198  const unit_type* i = unit_types.find(new_id);
199  if(!i) throw unit_type::error("unknown unit type: " + type_id);
200  return *i;
201 }
202 
203 static unit_race::GENDER generate_gender(const unit_type& type, bool random_gender)
204 {
205  const std::vector<unit_race::GENDER>& genders = type.genders();
206  assert(genders.size() > 0);
207 
208  if(random_gender == false || genders.size() == 1) {
209  return genders.front();
210  } else {
211  return genders[randomness::generator->get_random_int(0,genders.size()-1)];
212  }
213 }
214 
215 static unit_race::GENDER generate_gender(const unit_type& u_type, const config& cfg)
216 {
217  const std::string& gender = cfg["gender"];
218  if(!gender.empty()) {
219  return string_gender(gender);
220  }
221 
222  return generate_gender(u_type, cfg["random_gender"].to_bool());
223 }
224 
225 // Copy constructor
226 unit::unit(const unit& o)
227  : std::enable_shared_from_this<unit>()
228  , loc_(o.loc_)
229  , advances_to_(o.advances_to_)
230  , type_(o.type_)
231  , type_name_(o.type_name_)
232  , race_(o.race_)
233  , id_(o.id_)
234  , name_(o.name_)
235  , underlying_id_(o.underlying_id_)
236  , undead_variation_(o.undead_variation_)
237  , variation_(o.variation_)
238  , hit_points_(o.hit_points_)
239  , max_hit_points_(o.max_hit_points_)
240  , experience_(o.experience_)
241  , max_experience_(o.max_experience_)
242  , level_(o.level_)
243  , recall_cost_(o.recall_cost_)
244  , canrecruit_(o.canrecruit_)
245  , recruit_list_(o.recruit_list_)
246  , alignment_(o.alignment_)
247  , flag_rgb_(o.flag_rgb_)
248  , image_mods_(o.image_mods_)
249  , unrenamable_(o.unrenamable_)
250  , side_(o.side_)
251  , gender_(o.gender_)
252  , formula_man_(new unit_formula_manager(o.formula_manager()))
253  , movement_(o.movement_)
254  , max_movement_(o.max_movement_)
255  , vision_(o.vision_)
256  , jamming_(o.jamming_)
257  , movement_type_(o.movement_type_)
258  , hold_position_(o.hold_position_)
259  , end_turn_(o.end_turn_)
260  , resting_(o.resting_)
261  , attacks_left_(o.attacks_left_)
262  , max_attacks_(o.max_attacks_)
263  , states_(o.states_)
264  , known_boolean_states_(o.known_boolean_states_)
265  , variables_(o.variables_)
266  , events_(o.events_)
267  , filter_recall_(o.filter_recall_)
268  , emit_zoc_(o.emit_zoc_)
269  , overlays_(o.overlays_)
270  , role_(o.role_)
271  , attacks_(o.attacks_)
272  , facing_(o.facing_)
273  , trait_names_(o.trait_names_)
274  , trait_descriptions_(o.trait_descriptions_)
275  , unit_value_(o.unit_value_)
276  , goto_(o.goto_)
277  , interrupted_move_(o.interrupted_move_)
278  , is_fearless_(o.is_fearless_)
279  , is_healthy_(o.is_healthy_)
280  , modification_descriptions_(o.modification_descriptions_)
281  , anim_comp_(new unit_animation_component(*this, *o.anim_comp_))
282  , hidden_(o.hidden_)
283  , hp_bar_scaling_(o.hp_bar_scaling_)
284  , xp_bar_scaling_(o.xp_bar_scaling_)
285  , modifications_(o.modifications_)
286  , abilities_(o.abilities_)
287  , advancements_(o.advancements_)
288  , description_(o.description_)
289  , special_notes_(o.special_notes_)
290  , usage_(o.usage_)
291  , halo_(o.halo_)
292  , ellipse_(o.ellipse_)
293  , random_traits_(o.random_traits_)
294  , generate_name_(o.generate_name_)
295  , upkeep_(o.upkeep_)
296  , profile_(o.profile_)
297  , small_profile_(o.small_profile_)
298  , changed_attributes_(o.changed_attributes_)
299  , invisibility_cache_()
300 {
301  // Copy the attacks rather than just copying references
302  for(auto& a : attacks_) {
303  a.reset(new attack_type(*a));
304  }
305 }
306 
308  : std::enable_shared_from_this<unit>()
309  , loc_()
310  , advances_to_()
311  , type_(nullptr)
312  , type_name_()
313  , race_(&unit_race::null_race)
314  , id_()
315  , name_()
316  , underlying_id_(0)
317  , undead_variation_()
318  , variation_()
319  , hit_points_(1)
320  , max_hit_points_(1)
321  , experience_(0)
322  , max_experience_(1)
323  , level_(0)
324  , recall_cost_(-1)
325  , canrecruit_(false)
326  , recruit_list_()
327  , alignment_()
328  , flag_rgb_()
329  , image_mods_()
330  , unrenamable_(false)
331  , side_(0)
332  , gender_(unit_race::NUM_GENDERS)
333  , formula_man_(new unit_formula_manager())
334  , movement_(0)
335  , max_movement_(0)
336  , vision_(-1)
337  , jamming_(0)
338  , movement_type_()
339  , hold_position_(false)
340  , end_turn_(false)
341  , resting_(false)
342  , attacks_left_(0)
343  , max_attacks_(0)
344  , states_()
345  , known_boolean_states_()
346  , variables_()
347  , events_()
348  , filter_recall_()
349  , emit_zoc_(0)
350  , overlays_()
351  , role_()
352  , attacks_()
353  , facing_(map_location::NDIRECTIONS)
354  , trait_names_()
355  , trait_descriptions_()
356  , unit_value_()
357  , goto_()
358  , interrupted_move_()
359  , is_fearless_(false)
360  , is_healthy_(false)
361  , modification_descriptions_()
362  , anim_comp_(new unit_animation_component(*this))
363  , hidden_(false)
364  , hp_bar_scaling_(0)
365  , xp_bar_scaling_(0)
366  , modifications_()
367  , abilities_()
368  , advancements_()
369  , description_()
370  , special_notes_()
371  , usage_()
372  , halo_()
373  , ellipse_()
374  , random_traits_(true)
375  , generate_name_(true)
376  , upkeep_(upkeep_full{})
377  , changed_attributes_(0)
378  , invisibility_cache_()
379 {
380 }
381 
382 void unit::init(const config& cfg, bool use_traits, const vconfig* vcfg)
383 {
384  loc_ = map_location(cfg["x"], cfg["y"], wml_loc());
385  type_ = &get_unit_type(cfg["parent_type"].blank() ? cfg["type"].str() : cfg["parent_type"].str());
387  id_ = cfg["id"].str();
388  variation_ = cfg["variation"].empty() ? type_->default_variation() : cfg["variation"].str();
389  canrecruit_ = cfg["canrecruit"].to_bool();
390  gender_ = generate_gender(*type_, cfg);
391  name_ = gender_value(cfg, gender_, "male_name", "female_name", "name").t_str();
392  role_ = cfg["role"].str();
393  //, facing_(map_location::NDIRECTIONS)
394  //, anim_comp_(new unit_animation_component(*this))
395  hidden_ = cfg["hidden"].to_bool(false);
396  hp_bar_scaling_ = cfg["hp_bar_scaling"].blank() ? type_->hp_bar_scaling() : cfg["hp_bar_scaling"];
397  xp_bar_scaling_ = cfg["xp_bar_scaling"].blank() ? type_->xp_bar_scaling() : cfg["xp_bar_scaling"];
398  random_traits_ = true;
399  generate_name_ = true;
400  side_ = cfg["side"].to_int();
401 
402  if(side_ <= 0) {
403  side_ = 1;
404  }
405 
407  underlying_id_ = n_unit::unit_id(cfg["underlying_id"].to_size_t());
409 
410  if(vcfg) {
411  const vconfig& filter_recall = vcfg->child("filter_recall");
412  if(!filter_recall.null())
413  filter_recall_ = filter_recall.get_config();
414 
415  const vconfig::child_list& events = vcfg->get_children("event");
416  for(const vconfig& e : events) {
417  events_.add_child("event", e.get_config());
418  }
419  } else {
420  filter_recall_ = cfg.child_or_empty("filter_recall");
421 
422  for(const config& unit_event : cfg.child_range("event")) {
423  events_.add_child("event", unit_event);
424  }
425  }
426 
429  }
430 
431  random_traits_ = cfg["random_traits"].to_bool(true);
432  facing_ = map_location::parse_direction(cfg["facing"]);
434 
435  for(const config& mods : cfg.child_range("modifications")) {
437  }
438 
439  generate_name_ = cfg["generate_name"].to_bool(true);
440 
441  // Apply the unit type's data to this unit.
442  advance_to(*type_, use_traits);
443 
444  if(const config::attribute_value* v = cfg.get("overlays")) {
445  auto overlays = utils::parenthetical_split(v->str(), ',');
446  if(overlays.size() > 0) {
447  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.");
448  config effect;
449  config o;
450  effect["apply_to"] = "overlay";
451  effect["add"] = v->str();
452  o.add_child("effect", effect);
453  add_modification("object", o);
454  }
455  }
456 
457  if(auto variables = cfg.optional_child("variables")) {
459  }
460 
461  if(const config::attribute_value* v = cfg.get("race")) {
462  if(const unit_race *r = unit_types.find_race(*v)) {
463  race_ = r;
464  } else {
466  }
467  }
468 
469  if(const config::attribute_value* v = cfg.get("level")) {
470  set_level(v->to_int(level_));
471  }
472 
473  if(const config::attribute_value* v = cfg.get("undead_variation")) {
474  set_undead_variation(v->str());
475  }
476 
477  if(const config::attribute_value* v = cfg.get("max_attacks")) {
478  set_max_attacks(std::max(0, v->to_int(1)));
479  }
480 
481  if(const config::attribute_value* v = cfg.get("zoc")) {
482  set_emit_zoc(v->to_bool(level_ > 0));
483  }
484 
485  if(const config::attribute_value* v = cfg.get("description")) {
486  description_ = *v;
487  }
488 
489  if(const config::attribute_value* v = cfg.get("cost")) {
490  unit_value_ = *v;
491  }
492 
493  if(const config::attribute_value* v = cfg.get("ellipse")) {
494  set_image_ellipse(*v);
495  }
496 
497  if(const config::attribute_value* v = cfg.get("halo")) {
498  set_image_halo(*v);
499  }
500 
501  if(const config::attribute_value* v = cfg.get("usage")) {
502  set_usage(*v);
503  }
504 
505  if(const config::attribute_value* v = cfg.get("profile")) {
506  set_big_profile(v->str());
507  }
508 
509  if(const config::attribute_value* v = cfg.get("small_profile")) {
510  set_small_profile(v->str());
511  }
512 
513  if(const config::attribute_value* v = cfg.get("max_hitpoints")) {
514  set_max_hitpoints(std::max(1, v->to_int(max_hit_points_)));
515  }
516  if(const config::attribute_value* v = cfg.get("max_moves")) {
517  set_total_movement(std::max(0, v->to_int(max_movement_)));
518  }
519  if(const config::attribute_value* v = cfg.get("max_experience")) {
520  set_max_experience(std::max(1, v->to_int(max_experience_)));
521  }
522 
523  vision_ = cfg["vision"].to_int(vision_);
524  jamming_ = cfg["jamming"].to_int(jamming_);
525 
526  advances_to_t temp_advances = utils::split(cfg["advances_to"]);
527  if(temp_advances.size() == 1 && temp_advances.front() == "null") {
529  } else if(temp_advances.size() >= 1 && !temp_advances.front().empty()) {
530  set_advances_to(temp_advances);
531  }
532 
533  if(auto ai = cfg.optional_child("ai")) {
534  formula_man_->read(*ai);
535  config ai_events;
536  for(config mai : ai->child_range("micro_ai")) {
537  mai.clear_children("filter");
538  mai.add_child("filter")["id"] = id();
539  mai["side"] = side();
540  mai["action"] = "add";
541  ai_events.add_child("micro_ai", mai);
542  }
543  for(config ca : ai->child_range("candidate_action")) {
544  ca.clear_children("filter_own");
545  ca.add_child("filter_own")["id"] = id();
546  // Sticky candidate actions not supported here (they cause a crash because the unit isn't on the map yet)
547  ca.remove_attribute("sticky");
548  std::string stage = "main_loop";
549  if(ca.has_attribute("stage")) {
550  stage = ca["stage"].str();
551  ca.remove_attribute("stage");
552  }
553  config mod{
554  "action", "add",
555  "side", side(),
556  "path", "stage[" + stage + "].candidate_action[]",
557  "candidate_action", ca,
558  };
559  ai_events.add_child("modify_ai", mod);
560  }
561  if(ai_events.all_children_count() > 0) {
563  }
564  }
565 
566  // Don't use the unit_type's attacks if this config has its own defined
567  if(config::const_child_itors cfg_range = cfg.child_range("attack")) {
569  attacks_.clear();
570  for(const config& c : cfg_range) {
571  attacks_.emplace_back(new attack_type(c));
572  }
573  }
574 
575  // Don't use the unit_type's special notes if this config has its own defined
576  if(config::const_child_itors cfg_range = cfg.child_range("special_note")) {
578  special_notes_.clear();
579  for(const config& c : cfg_range) {
580  special_notes_.emplace_back(c["note"].t_str());
581  }
582  }
583 
584  // If cfg specifies [advancement]s, replace this [advancement]s with them.
585  if(cfg.has_child("advancement")) {
587  advancements_.clear();
588  for(const config& adv : cfg.child_range("advancement")) {
589  advancements_.push_back(adv);
590  }
591  }
592 
593  // Don't use the unit_type's abilities if this config has its own defined
594  // Why do we allow multiple [abilities] tags?
595  if(config::const_child_itors cfg_range = cfg.child_range("abilities")) {
597  abilities_.clear();
598  for(const config& abilities : cfg_range) {
600  }
601  }
602 
603  if(const config::attribute_value* v = cfg.get("alignment")) {
605  auto new_align = unit_alignments::get_enum(v->str());
606  if(new_align) {
607  alignment_ = *new_align;
608  }
609  }
610 
611  // Adjust the unit's defense, movement, vision, jamming, resistances, and
612  // flying status if this config has its own defined.
613  if(cfg.has_child("movement_costs")
614  || cfg.has_child("vision_costs")
615  || cfg.has_child("jamming_costs")
616  || cfg.has_child("defense")
617  || cfg.has_child("resistance")
618  || cfg.has_attribute("flying"))
619  {
621  }
622 
623  movement_type_.merge(cfg);
624 
625  if(auto status_flags = cfg.optional_child("status")) {
626  for(const config::attribute &st : status_flags->attribute_range()) {
627  if(st.second.to_bool()) {
628  set_state(st.first, true);
629  }
630  }
631  }
632 
633  if(cfg["ai_special"] == "guardian") {
634  set_state(STATE_GUARDIAN, true);
635  }
636 
637  if(const config::attribute_value* v = cfg.get("invulnerable")) {
638  set_state(STATE_INVULNERABLE, v->to_bool());
639  }
640 
641  goto_.set_wml_x(cfg["goto_x"].to_int());
642  goto_.set_wml_y(cfg["goto_y"].to_int());
643 
644  attacks_left_ = std::max(0, cfg["attacks_left"].to_int(max_attacks_));
645 
646  movement_ = std::max(0, cfg["moves"].to_int(max_movement_));
647  // we allow negative hitpoints, one of the reasons is that a unit
648  // might be stored+unstored during a attack related event before it
649  // dies when it has negative hp and when dont want the event to
650  // change the unit hp when it was not intended.
651  hit_points_ = cfg["hitpoints"].to_int(max_hit_points_);
652 
653  experience_ = cfg["experience"];
654  resting_ = cfg["resting"].to_bool();
655  unrenamable_ = cfg["unrenamable"].to_bool();
656 
657  // We need to check to make sure that the cfg is not blank and if it
658  // isn't pull that value otherwise it goes with the default of -1.
659  if(!cfg["recall_cost"].blank()) {
660  recall_cost_ = cfg["recall_cost"].to_int(recall_cost_);
661  }
662 
663  generate_name();
664 
665  parse_upkeep(cfg["upkeep"]);
666 
667  set_recruits(utils::split(cfg["extra_recruit"]));
668 
669  warn_unknown_attribute(cfg.attribute_range());
670 
671 #if 0
672  // Debug unit animations for units as they appear in game
673  for(const auto& anim : anim_comp_->animations_) {
674  std::cout << anim.debug() << std::endl;
675  }
676 #endif
677 }
678 
680 {
681  for(auto& u : units_with_cache) {
682  u->clear_visibility_cache();
683  }
684 
685  units_with_cache.clear();
686 }
687 
688 void unit::init(const unit_type& u_type, int side, bool real_unit, unit_race::GENDER gender, const std::string& variation)
689 {
690  type_ = &u_type;
693  side_ = side;
694  gender_ = gender != unit_race::NUM_GENDERS ? gender : generate_gender(u_type, real_unit);
696  upkeep_ = upkeep_full{};
697 
698  // Apply the unit type's data to this unit.
699  advance_to(u_type, real_unit);
700 
701  if(real_unit) {
702  generate_name();
703  }
704 
706 
707  // Set these after traits and modifications have set the maximums.
711 }
712 
714 {
715  try {
716  anim_comp_->clear_haloes();
717 
718  // Remove us from the status cache
719  auto itor = std::find(units_with_cache.begin(), units_with_cache.end(), this);
720 
721  if(itor != units_with_cache.end()) {
722  units_with_cache.erase(itor);
723  }
724  } catch(const std::exception & e) {
725  ERR_UT << "Caught exception when destroying unit: " << e.what();
726  } catch(...) {
727  DBG_UT << "Caught general exception when destroying unit: " << utils::get_unknown_exception_type();
728  }
729 }
730 
732 {
733  if(!name_.empty() || !generate_name_) {
734  return;
735  }
737  generate_name_ = false;
738 }
739 
740 void unit::generate_traits(bool must_have_only)
741 {
742  LOG_UT << "Generating a trait for unit type " << type().log_id() << " with must_have_only " << must_have_only;
743  const unit_type& u_type = type();
744 
745  config::const_child_itors current_traits = modifications_.child_range("trait");
746 
747  // Handle must-have only at the beginning
748  for(const config& t : u_type.possible_traits()) {
749  // Skip the trait if the unit already has it.
750  const std::string& tid = t["id"];
751  bool already = false;
752  for(const config& mod : current_traits) {
753  if(mod["id"] == tid) {
754  already = true;
755  break;
756  }
757  }
758  if(already) {
759  continue;
760  }
761  // Add the trait if it is mandatory.
762  const std::string& avl = t["availability"];
763  if(avl == "musthave") {
764  modifications_.add_child("trait", t);
765  current_traits = modifications_.child_range("trait");
766  continue;
767  }
768  }
769 
770  if(must_have_only) {
771  return;
772  }
773 
774  std::vector<const config*> candidate_traits;
775  std::vector<std::string> temp_require_traits;
776  std::vector<std::string> temp_exclude_traits;
777 
778  // Now randomly fill out to the number of traits required or until
779  // there aren't any more traits.
780  int nb_traits = current_traits.size();
781  int max_traits = u_type.num_traits();
782  for(; nb_traits < max_traits; ++nb_traits)
783  {
784  current_traits = modifications_.child_range("trait");
785  candidate_traits.clear();
786  for(const config& t : u_type.possible_traits()) {
787  // Skip the trait if the unit already has it.
788  const std::string& tid = t["id"];
789  bool already = false;
790  for(const config& mod : current_traits) {
791  if(mod["id"] == tid) {
792  already = true;
793  break;
794  }
795  }
796 
797  if(already) {
798  continue;
799  }
800  // Skip trait if trait requirements are not met
801  // or trait exclusions are present
802  temp_require_traits = utils::split(t["require_traits"]);
803  temp_exclude_traits = utils::split(t["exclude_traits"]);
804 
805  // See if the unit already has a trait that excludes the current one
806  for(const config& mod : current_traits) {
807  if (mod["exclude_traits"] != "") {
808  for (const auto& c: utils::split(mod["exclude_traits"])) {
809  temp_exclude_traits.push_back(c);
810  }
811  }
812  }
813 
814  // First check for requirements
815  bool trait_req_met = true;
816  for(const std::string& s : temp_require_traits) {
817  bool has_trait = false;
818  for(const config& mod : current_traits) {
819  if (mod["id"] == s)
820  has_trait = true;
821  }
822  if(!has_trait) {
823  trait_req_met = false;
824  break;
825  }
826  }
827  if(!trait_req_met) {
828  continue;
829  }
830 
831  // Now check for exclusionary traits
832  bool trait_exc_met = true;
833 
834  for(const std::string& s : temp_exclude_traits) {
835  bool has_exclusionary_trait = false;
836  for(const config& mod : current_traits) {
837  if (mod["id"] == s)
838  has_exclusionary_trait = true;
839  }
840  if (tid == s) {
841  has_exclusionary_trait = true;
842  }
843  if(has_exclusionary_trait) {
844  trait_exc_met = false;
845  break;
846  }
847  }
848  if(!trait_exc_met) {
849  continue;
850  }
851 
852  const std::string& avl = t["availability"];
853  // The trait is still available, mark it as a candidate for randomizing.
854  // For leaders, only traits with availability "any" are considered.
855  if(!must_have_only && (!can_recruit() || avl == "any")) {
856  candidate_traits.push_back(&t);
857  }
858  }
859  // No traits available anymore? Break
860  if(candidate_traits.empty()) {
861  break;
862  }
863 
864  int num = randomness::generator->get_random_int(0,candidate_traits.size()-1);
865  modifications_.add_child("trait", *candidate_traits[num]);
866  candidate_traits.erase(candidate_traits.begin() + num);
867  }
868  // Once random traits are added, don't do it again.
869  // Such as when restoring a saved character.
870  random_traits_ = false;
871 }
872 
873 std::vector<std::string> unit::get_traits_list() const
874 {
875  std::vector<std::string> res;
876 
877  for(const config& mod : modifications_.child_range("trait"))
878  {
879  // Make sure to return empty id trait strings as otherwise
880  // names will not match in length (Bug #21967)
881  res.push_back(mod["id"]);
882  }
883  return res;
884 }
885 
886 
887 /**
888  * Advances this unit to the specified type.
889  * Experience is left unchanged.
890  * Current hit point total is left unchanged unless it would violate max HP.
891  * Assumes gender_ and variation_ are set to their correct values.
892  */
893 void unit::advance_to(const unit_type& u_type, bool use_traits)
894 {
895  appearance_changed_ = true;
896  // For reference, the type before this advancement.
897  const unit_type& old_type = type();
898  // Adjust the new type for gender and variation.
900  // In case u_type was already a variation, make sure our variation is set correctly.
901  variation_ = new_type.variation_id();
902 
903  // Reset the scalar values first
904  trait_names_.clear();
905  trait_descriptions_.clear();
906  is_fearless_ = false;
907  is_healthy_ = false;
908  image_mods_.clear();
909  overlays_.clear();
910  ellipse_.reset();
911 
912  // Clear modification-related caches
914 
915 
916  if(!new_type.usage().empty()) {
917  set_usage(new_type.usage());
918  }
919 
920  set_image_halo(new_type.halo());
921  if(!new_type.ellipse().empty()) {
922  set_image_ellipse(new_type.ellipse());
923  }
924 
925  generate_name_ &= new_type.generate_name();
926  abilities_ = new_type.abilities_cfg();
927  advancements_.clear();
928 
929  for(const config& advancement : new_type.advancements()) {
930  advancements_.push_back(advancement);
931  }
932 
933  // If unit has specific profile, remember it and keep it after advancing
934  if(small_profile_.empty() || small_profile_ == old_type.small_profile()) {
935  small_profile_ = new_type.small_profile();
936  }
937 
938  if(profile_.empty() || profile_ == old_type.big_profile()) {
939  profile_ = new_type.big_profile();
940  }
941  // NOTE: There should be no need to access old_cfg (or new_cfg) after this
942  // line. Particularly since the swap might have affected old_cfg.
943 
944  advances_to_ = new_type.advances_to();
945 
946  race_ = new_type.race();
947  type_ = &new_type;
948  type_name_ = new_type.type_name();
949  description_ = new_type.unit_description();
951  undead_variation_ = new_type.undead_variation();
952  max_experience_ = new_type.experience_needed(true);
953  level_ = new_type.level();
954  recall_cost_ = new_type.recall_cost();
955  alignment_ = new_type.alignment();
956  max_hit_points_ = new_type.hitpoints();
957  hp_bar_scaling_ = new_type.hp_bar_scaling();
958  xp_bar_scaling_ = new_type.xp_bar_scaling();
959  max_movement_ = new_type.movement();
960  vision_ = new_type.vision(true);
961  jamming_ = new_type.jamming();
962  movement_type_ = new_type.movement_type();
963  emit_zoc_ = new_type.has_zoc();
964  attacks_.clear();
965  std::transform(new_type.attacks().begin(), new_type.attacks().end(), std::back_inserter(attacks_), [](const attack_type& atk) {
966  return std::make_shared<attack_type>(atk);
967  });
968  unit_value_ = new_type.cost();
969 
970  max_attacks_ = new_type.max_attacks();
971 
972  flag_rgb_ = new_type.flag_rgb();
973 
974  upkeep_ = upkeep_full{};
975  parse_upkeep(new_type.get_cfg()["upkeep"]);
976 
977  anim_comp_->reset_after_advance(&new_type);
978 
979  if(random_traits_) {
980  generate_traits(!use_traits);
981  } else {
982  // This will add any "musthave" traits to the new unit that it doesn't already have.
983  // This covers the Dark Sorcerer advancing to Lich and gaining the "undead" trait,
984  // but random and/or optional traits are not added,
985  // and neither are inappropriate traits removed.
986  generate_traits(true);
987  }
988 
989  // Apply modifications etc, refresh the unit.
990  // This needs to be after type and gender are fixed,
991  // since there can be filters on the modifications
992  // that may result in different effects after the advancement.
994 
995  // Now that modifications are done modifying traits, check if poison should
996  // be cleared.
997  if(get_state("unpoisonable")) {
998  set_state(STATE_POISONED, false);
999  }
1000  if(get_state("unslowable")) {
1001  set_state(STATE_SLOWED, false);
1002  }
1003  if(get_state("unpetrifiable")) {
1004  set_state(STATE_PETRIFIED, false);
1005  }
1006 
1007  // Now that modifications are done modifying the maximum hit points,
1008  // enforce this maximum.
1011  }
1012 
1013  // In case the unit carries EventWML, apply it now
1016  }
1017  bool bool_small_profile = get_attr_changed(UA_SMALL_PROFILE);
1018  bool bool_profile = get_attr_changed(UA_PROFILE);
1020  if(bool_small_profile && small_profile_ != new_type.small_profile()) {
1022  }
1023 
1024  if(bool_profile && profile_ != new_type.big_profile()) {
1026  }
1027 }
1028 
1029 std::string unit::big_profile() const
1030 {
1031  if(!profile_.empty() && profile_ != "unit_image") {
1032  return profile_;
1033  }
1034 
1035  return absolute_image();
1036 }
1037 
1038 std::string unit::small_profile() const
1039 {
1040  if(!small_profile_.empty() && small_profile_ != "unit_image") {
1041  return small_profile_;
1042  }
1043 
1044  if(!profile_.empty() && small_profile_ != "unit_image" && profile_ != "unit_image") {
1045  return profile_;
1046  }
1047 
1048  return absolute_image();
1049 }
1050 
1051 const std::string& unit::leader_crown()
1052 {
1053  return leader_crown_path;
1054 }
1055 
1056 const std::string& unit::flag_rgb() const
1057 {
1058  return flag_rgb_.empty() ? game_config::unit_rgb : flag_rgb_;
1059 }
1060 
1061 static color_t hp_color_impl(int hitpoints, int max_hitpoints)
1062 {
1063  double unit_energy = 0.0;
1064  color_t energy_color {0,0,0,255};
1065 
1066  if(max_hitpoints > 0) {
1067  unit_energy = static_cast<double>(hitpoints)/static_cast<double>(max_hitpoints);
1068  }
1069 
1070  if(1.0 == unit_energy) {
1071  energy_color.r = 33;
1072  energy_color.g = 225;
1073  energy_color.b = 0;
1074  } else if(unit_energy > 1.0) {
1075  energy_color.r = 100;
1076  energy_color.g = 255;
1077  energy_color.b = 100;
1078  } else if(unit_energy >= 0.75) {
1079  energy_color.r = 170;
1080  energy_color.g = 255;
1081  energy_color.b = 0;
1082  } else if(unit_energy >= 0.5) {
1083  energy_color.r = 255;
1084  energy_color.g = 175;
1085  energy_color.b = 0;
1086  } else if(unit_energy >= 0.25) {
1087  energy_color.r = 255;
1088  energy_color.g = 155;
1089  energy_color.b = 0;
1090  } else {
1091  energy_color.r = 255;
1092  energy_color.g = 0;
1093  energy_color.b = 0;
1094  }
1095 
1096  return energy_color;
1097 }
1098 
1100 {
1101  return hp_color_impl(hitpoints(), max_hitpoints());
1102 }
1103 
1104 color_t unit::hp_color(int new_hitpoints) const
1105 {
1106  return hp_color_impl(new_hitpoints, hitpoints());
1107 }
1108 
1110 {
1111  return hp_color_impl(1, 1);
1112 }
1113 
1114 color_t unit::xp_color(int xp_to_advance, bool can_advance, bool has_amla)
1115 {
1116  const color_t near_advance_color {255,255,255,255};
1117  const color_t mid_advance_color {150,255,255,255};
1118  const color_t far_advance_color {0,205,205,255};
1119  const color_t normal_color {0,160,225,255};
1120  const color_t near_amla_color {225,0,255,255};
1121  const color_t mid_amla_color {169,30,255,255};
1122  const color_t far_amla_color {139,0,237,255};
1123  const color_t amla_color {170,0,255,255};
1124 
1125  const bool near_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience;
1126  const bool mid_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience*2;
1127  const bool far_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience*3;
1128 
1129  color_t color = normal_color;
1130  if(can_advance){
1131  if(near_advance){
1132  color=near_advance_color;
1133  } else if(mid_advance){
1134  color=mid_advance_color;
1135  } else if(far_advance){
1136  color=far_advance_color;
1137  }
1138  } else if(has_amla){
1139  if(near_advance){
1140  color=near_amla_color;
1141  } else if(mid_advance){
1142  color=mid_amla_color;
1143  } else if(far_advance){
1144  color=far_amla_color;
1145  } else {
1146  color=amla_color;
1147  }
1148  }
1149 
1150  return(color);
1151 }
1152 
1154 {
1155  bool major_amla = false;
1156  bool has_amla = false;
1157  for(const config& adv:get_modification_advances()){
1158  major_amla |= adv["major_amla"].to_bool();
1159  has_amla = true;
1160  }
1161  //TODO: calculating has_amla and major_amla can be a quite slow operation, we should cache these two values somehow.
1162  return xp_color(experience_to_advance(), !advances_to().empty() || major_amla, has_amla);
1163 }
1164 
1165 void unit::set_recruits(const std::vector<std::string>& recruits)
1166 {
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;
1180  }
1181  }
1182 
1183  return result;
1184 }
1185 
1186 void unit::set_advances_to(const std::vector<std::string>& advances_to)
1187 {
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_.mandatory_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  {"invulnerable", STATE_INVULNERABLE},
1375 };
1376 
1377 void unit::set_state(const std::string& state, bool value)
1378 {
1379  appearance_changed_ = true;
1380  state_t known_boolean_state_id = get_known_boolean_state_id(state);
1381  if(known_boolean_state_id != STATE_UNKNOWN) {
1382  set_state(known_boolean_state_id, value);
1383  return;
1384  }
1385 
1386  // Backwards compatibility for not_living. Don't remove before 1.12
1387  if(state == "not_living") {
1388  set_state("undrainable", value);
1389  set_state("unpoisonable", value);
1390  set_state("unplagueable", value);
1391  }
1392 
1393  if(value) {
1394  states_.insert(state);
1395  } else {
1396  states_.erase(state);
1397  }
1398 }
1399 
1400 bool unit::has_ability_by_id(const std::string& ability) const
1401 {
1402  for(const config::any_child ab : abilities_.all_children_range()) {
1403  if(ab.cfg["id"] == ability) {
1404  return true;
1405  }
1406  }
1407 
1408  return false;
1409 }
1410 
1411 void unit::remove_ability_by_id(const std::string& ability)
1412 {
1415  while (i != abilities_.ordered_end()) {
1416  if(i->cfg["id"] == ability) {
1417  i = abilities_.erase(i);
1418  } else {
1419  ++i;
1420  }
1421  }
1422 }
1423 
1424 static bool type_value_if_present(const config& filter, const config& cfg)
1425 {
1426  if(filter["type_value"].empty()) {
1427  return true;
1428  }
1429 
1430  std::string cfg_type_value;
1431  const std::vector<std::string> filter_attribute = utils::split(filter["type_value"]);
1432  if(!cfg["value"].empty()){
1433  cfg_type_value ="value";
1434  } else if(!cfg["add"].empty()){
1435  cfg_type_value ="add";
1436  } else if(!cfg["sub"].empty()){
1437  cfg_type_value ="sub";
1438  } else if(!cfg["multiply"].empty()){
1439  cfg_type_value ="multiply";
1440  } else if(!cfg["divide"].empty()){
1441  cfg_type_value ="divide";
1442  }
1443  return ( std::find(filter_attribute.begin(), filter_attribute.end(), cfg_type_value) != filter_attribute.end() );
1444 }
1445 
1446 static bool matches_ability_filter(const config & cfg, const std::string& tag_name, const config & filter)
1447 {
1448  using namespace utils::config_filters;
1449 
1450  if(!filter["affect_adjacent"].empty()){
1451  bool adjacent = cfg.has_child("affect_adjacent");
1452  if(filter["affect_adjacent"].to_bool() != adjacent){
1453  return false;
1454  }
1455  }
1456 
1457  if(!bool_matches_if_present(filter, cfg, "affect_self", true))
1458  return false;
1459 
1460  if(!bool_matches_if_present(filter, cfg, "affect_allies", true))
1461  return false;
1462 
1463  if(!bool_matches_if_present(filter, cfg, "affect_enemies", false))
1464  return false;
1465 
1466  if(!bool_matches_if_present(filter, cfg, "cumulative", false))
1467  return false;
1468 
1469  const std::vector<std::string> filter_type = utils::split(filter["tag_name"]);
1470  if ( !filter_type.empty() && std::find(filter_type.begin(), filter_type.end(), tag_name) == filter_type.end() )
1471  return false;
1472 
1473  if(!string_matches_if_present(filter, cfg, "id", ""))
1474  return false;
1475 
1476  if(!string_matches_if_present(filter, cfg, "apply_to", "self"))
1477  return false;
1478 
1479  if(!string_matches_if_present(filter, cfg, "overwrite_specials", "none"))
1480  return false;
1481 
1482  if(!string_matches_if_present(filter, cfg, "active_on", "both"))
1483  return false;
1484 
1485  if(!int_matches_if_present(filter, cfg, "value"))
1486  return false;
1487 
1488  if(!int_matches_if_present_or_negative(filter, cfg, "add", "sub"))
1489  return false;
1490 
1491  if(!int_matches_if_present_or_negative(filter, cfg, "sub", "add"))
1492  return false;
1493 
1494  if(!double_matches_if_present(filter, cfg, "multiply"))
1495  return false;
1496 
1497  if(!double_matches_if_present(filter, cfg, "divide"))
1498  return false;
1499 
1500  if(!type_value_if_present(filter, cfg))
1501  return false;
1502 
1503  // Passed all tests.
1504  return true;
1505 }
1506 
1507 bool unit::ability_matches_filter(const config & cfg, const std::string& tag_name, const config & filter) const
1508 {
1509  // Handle the basic filter.
1510  bool matches = matches_ability_filter(cfg, tag_name, filter);
1511 
1512  // Handle [and], [or], and [not] with in-order precedence
1513  for (const config::any_child condition : filter.all_children_range() )
1514  {
1515  // Handle [and]
1516  if ( condition.key == "and" )
1517  matches = matches && ability_matches_filter(cfg, tag_name, condition.cfg);
1518 
1519  // Handle [or]
1520  else if ( condition.key == "or" )
1521  matches = matches || ability_matches_filter(cfg, tag_name, condition.cfg);
1522 
1523  // Handle [not]
1524  else if ( condition.key == "not" )
1525  matches = matches && !ability_matches_filter(cfg, tag_name, condition.cfg);
1526  }
1527 
1528  return matches;
1529 }
1530 
1532 {
1535  while (i != abilities_.ordered_end()) {
1536  if(ability_matches_filter(i->cfg, i->key, filter)) {
1537  i = abilities_.erase(i);
1538  } else {
1539  ++i;
1540  }
1541  }
1542 }
1543 
1545 {
1546  for(const auto& a_ptr : attacks_) {
1547  if(a_ptr->get_changed()) {
1548  return true;
1549  }
1550 
1551  }
1552  return false;
1553 }
1554 void unit::write(config& cfg, bool write_all) const
1555 {
1556  config back;
1557  auto write_subtag = [&](const std::string& key, const config& child)
1558  {
1559  cfg.clear_children(key);
1560 
1561  if(!child.empty()) {
1562  cfg.add_child(key, child);
1563  } else {
1564  back.add_child(key, child);
1565  }
1566  };
1567 
1568  if(write_all || get_attr_changed(UA_MOVEMENT_TYPE)) {
1569  movement_type_.write(cfg, false);
1570  }
1571  if(write_all || get_attr_changed(UA_SMALL_PROFILE)) {
1572  cfg["small_profile"] = small_profile_;
1573  }
1574  if(write_all || get_attr_changed(UA_PROFILE)) {
1575  cfg["profile"] = profile_;
1576  }
1577  if(description_ != type().unit_description()) {
1578  cfg["description"] = description_;
1579  }
1580  if(write_all || get_attr_changed(UA_NOTES)) {
1581  for(const t_string& note : special_notes_) {
1582  cfg.add_child("special_note")["note"] = note;
1583  }
1584  }
1585 
1586  if(halo_) {
1587  cfg["halo"] = *halo_;
1588  }
1589 
1590  if(ellipse_) {
1591  cfg["ellipse"] = *ellipse_;
1592  }
1593 
1594  if(usage_) {
1595  cfg["usage"] = *usage_;
1596  }
1597 
1598  write_upkeep(cfg["upkeep"]);
1599 
1600  cfg["hitpoints"] = hit_points_;
1601  if(write_all || get_attr_changed(UA_MAX_HP)) {
1602  cfg["max_hitpoints"] = max_hit_points_;
1603  }
1604  cfg["image_icon"] = type().icon();
1605  cfg["image"] = type().image();
1606  cfg["random_traits"] = random_traits_;
1607  cfg["generate_name"] = generate_name_;
1608  cfg["experience"] = experience_;
1609  if(write_all || get_attr_changed(UA_MAX_XP)) {
1610  cfg["max_experience"] = max_experience_;
1611  }
1612  cfg["recall_cost"] = recall_cost_;
1613 
1614  cfg["side"] = side_;
1615 
1616  cfg["type"] = type_id();
1617 
1618  if(type_id() != type().parent_id()) {
1619  cfg["parent_type"] = type().parent_id();
1620  }
1621 
1622  // Support for unit formulas in [ai] and unit-specific variables in [ai] [vars]
1623  formula_man_->write(cfg);
1624 
1625  cfg["gender"] = gender_string(gender_);
1626  cfg["variation"] = variation_;
1627  cfg["role"] = role_;
1628 
1629  config status_flags;
1630  for(const std::string& state : get_states()) {
1631  status_flags[state] = true;
1632  }
1633 
1634  write_subtag("variables", variables_);
1635  write_subtag("filter_recall", filter_recall_);
1636  write_subtag("status", status_flags);
1637 
1638  cfg.clear_children("events");
1639  cfg.append(events_);
1640 
1641  // Overlays are exported as the modifications that add them, not as an overlays= value,
1642  // however removing the key breaks the Gui Debug Tools.
1643  // \todo does anything depend on the key's value, other than the re-import code in unit::init?
1644  cfg["overlays"] = "";
1645 
1646  cfg["name"] = name_;
1647  cfg["id"] = id_;
1648  cfg["underlying_id"] = underlying_id_.value;
1649 
1650  if(can_recruit()) {
1651  cfg["canrecruit"] = true;
1652  }
1653 
1654  cfg["extra_recruit"] = utils::join(recruit_list_);
1655 
1656  cfg["facing"] = map_location::write_direction(facing_);
1657 
1658  cfg["goto_x"] = goto_.wml_x();
1659  cfg["goto_y"] = goto_.wml_y();
1660 
1661  cfg["moves"] = movement_;
1662  if(write_all || get_attr_changed(UA_MAX_MP)) {
1663  cfg["max_moves"] = max_movement_;
1664  }
1665  cfg["vision"] = vision_;
1666  cfg["jamming"] = jamming_;
1667 
1668  cfg["resting"] = resting_;
1669 
1670  if(write_all || get_attr_changed(UA_ADVANCE_TO)) {
1671  cfg["advances_to"] = utils::join(advances_to_);
1672  }
1673 
1674  cfg["race"] = race_->id();
1675  cfg["language_name"] = type_name_;
1676  cfg["undead_variation"] = undead_variation_;
1677  if(write_all || get_attr_changed(UA_LEVEL)) {
1678  cfg["level"] = level_;
1679  }
1680  if(write_all || get_attr_changed(UA_ALIGNMENT)) {
1681  cfg["alignment"] = unit_alignments::get_string(alignment_);
1682  }
1683  cfg["flag_rgb"] = flag_rgb_;
1684  cfg["unrenamable"] = unrenamable_;
1685 
1686  cfg["attacks_left"] = attacks_left_;
1687  if(write_all || get_attr_changed(UA_MAX_AP)) {
1688  cfg["max_attacks"] = max_attacks_;
1689  }
1690  if(write_all || get_attr_changed(UA_ZOC)) {
1691  cfg["zoc"] = emit_zoc_;
1692  }
1693  cfg["hidden"] = hidden_;
1694 
1695  if(write_all || get_attr_changed(UA_ATTACKS) || get_attacks_changed()) {
1696  cfg.clear_children("attack");
1697  for(attack_ptr i : attacks_) {
1698  i->write(cfg.add_child("attack"));
1699  }
1700  }
1701 
1702  cfg["cost"] = unit_value_;
1703 
1704  write_subtag("modifications", modifications_);
1705  if(write_all || get_attr_changed(UA_ABILITIES)) {
1706  write_subtag("abilities", abilities_);
1707  }
1708  if(write_all || get_attr_changed(UA_ADVANCEMENTS)) {
1709  cfg.clear_children("advancement");
1710  for(const config& advancement : advancements_) {
1711  if(!advancement.empty()) {
1712  cfg.add_child("advancement", advancement);
1713  }
1714  }
1715  }
1716  cfg.append(back);
1717 }
1718 
1720 {
1721  if(dir != map_location::NDIRECTIONS && dir != facing_) {
1722  appearance_changed_ = true;
1723  facing_ = dir;
1724  }
1725  // Else look at yourself (not available so continue to face the same direction)
1726 }
1727 
1728 int unit::upkeep() const
1729 {
1730  // Leaders do not incur upkeep.
1731  if(can_recruit()) {
1732  return 0;
1733  }
1734 
1735  return utils::visit(upkeep_value_visitor{*this}, upkeep_);
1736 }
1737 
1738 bool unit::loyal() const
1739 {
1740  return utils::holds_alternative<upkeep_loyal>(upkeep_);
1741 }
1742 
1744 {
1745  int def = movement_type_.defense_modifier(terrain);
1746 #if 0
1747  // A [defense] ability is too costly and doesn't take into account target locations.
1748  // Left as a comment in case someone ever wonders why it isn't a good idea.
1749  unit_ability_list defense_abilities = get_abilities("defense");
1750  if(!defense_abilities.empty()) {
1751  unit_abilities::effect defense_effect(defense_abilities, def);
1752  def = defense_effect.get_composite_value();
1753  }
1754 #endif
1755  return def;
1756 }
1757 
1758 bool unit::resistance_filter_matches(const config& cfg, bool attacker, const std::string& damage_name, int res) const
1759 {
1760  if(!(cfg["active_on"].empty() || (attacker && cfg["active_on"] == "offense") || (!attacker && cfg["active_on"] == "defense"))) {
1761  return false;
1762  }
1763 
1764  const std::string& apply_to = cfg["apply_to"];
1765  if(!apply_to.empty()) {
1766  if(damage_name != apply_to) {
1767  if(apply_to.find(',') != std::string::npos &&
1768  apply_to.find(damage_name) != std::string::npos) {
1769  const std::vector<std::string>& vals = utils::split(apply_to);
1770  if(std::find(vals.begin(),vals.end(),damage_name) == vals.end()) {
1771  return false;
1772  }
1773  } else {
1774  return false;
1775  }
1776  }
1777  }
1778 
1779  if(!unit_abilities::filter_base_matches(cfg, res)) {
1780  return false;
1781  }
1782 
1783  return true;
1784 }
1785 
1786 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
1787 {
1788  int res = movement_type_.resistance_against(damage_name);
1789 
1790  unit_ability_list resistance_abilities = get_abilities_weapons("resistance",loc, weapon, opp_weapon);
1791  utils::erase_if(resistance_abilities, [&](const unit_ability& i) {
1792  return !resistance_filter_matches(*i.ability_cfg, attacker, damage_name, 100-res);
1793  });
1794 
1795  if(!resistance_abilities.empty()) {
1796  unit_abilities::effect resist_effect(resistance_abilities, 100-res);
1797 
1798  res = 100 - std::min<int>(
1799  resist_effect.get_composite_value(),
1800  resistance_abilities.highest("max_value").first
1801  );
1802  }
1803 
1804  return res;
1805 }
1806 
1807 std::map<std::string, std::string> unit::advancement_icons() const
1808 {
1809  std::map<std::string,std::string> temp;
1810  if(!can_advance()) {
1811  return temp;
1812  }
1813 
1814  if(!advances_to_.empty()) {
1815  std::ostringstream tooltip;
1816  const std::string& image = game_config::images::level;
1817 
1818  for(const std::string& s : advances_to()) {
1819  if(!s.empty()) {
1820  tooltip << s << std::endl;
1821  }
1822  }
1823 
1824  temp[image] = tooltip.str();
1825  }
1826 
1827  for(const config& adv : get_modification_advances()) {
1828  const std::string& image = adv["image"];
1829  if(image.empty()) {
1830  continue;
1831  }
1832 
1833  std::ostringstream tooltip;
1834  tooltip << temp[image];
1835 
1836  const std::string& tt = adv["description"];
1837  if(!tt.empty()) {
1838  tooltip << tt << std::endl;
1839  }
1840 
1841  temp[image] = tooltip.str();
1842  }
1843 
1844  return(temp);
1845 }
1846 
1847 std::vector<std::pair<std::string, std::string>> unit::amla_icons() const
1848 {
1849  std::vector<std::pair<std::string, std::string>> temp;
1850  std::pair<std::string, std::string> icon; // <image,tooltip>
1851 
1852  for(const config& adv : get_modification_advances()) {
1853  icon.first = adv["icon"].str();
1854  icon.second = adv["description"].str();
1855 
1856  for(unsigned j = 0, j_count = modification_count("advancement", adv["id"]); j < j_count; ++j) {
1857  temp.push_back(icon);
1858  }
1859  }
1860 
1861  return(temp);
1862 }
1863 
1864 std::vector<config> unit::get_modification_advances() const
1865 {
1866  std::vector<config> res;
1867  for(const config& adv : modification_advancements()) {
1868  if(adv["strict_amla"].to_bool() && !advances_to_.empty()) {
1869  continue;
1870  }
1871  if(auto filter = adv.optional_child("filter")) {
1872  if(!unit_filter(vconfig(*filter)).matches(*this, loc_)) {
1873  continue;
1874  }
1875  }
1876 
1877  if(modification_count("advancement", adv["id"]) >= static_cast<unsigned>(adv["max_times"].to_int(1))) {
1878  continue;
1879  }
1880 
1881  std::vector<std::string> temp_require = utils::split(adv["require_amla"]);
1882  std::vector<std::string> temp_exclude = utils::split(adv["exclude_amla"]);
1883 
1884  if(temp_require.empty() && temp_exclude.empty()) {
1885  res.push_back(adv);
1886  continue;
1887  }
1888 
1889  std::sort(temp_require.begin(), temp_require.end());
1890  std::sort(temp_exclude.begin(), temp_exclude.end());
1891 
1892  std::vector<std::string> uniq_require, uniq_exclude;
1893 
1894  std::unique_copy(temp_require.begin(), temp_require.end(), std::back_inserter(uniq_require));
1895  std::unique_copy(temp_exclude.begin(), temp_exclude.end(), std::back_inserter(uniq_exclude));
1896 
1897  bool exclusion_found = false;
1898  for(const std::string& s : uniq_exclude) {
1899  int max_num = std::count(temp_exclude.begin(), temp_exclude.end(), s);
1900  int mod_num = modification_count("advancement", s);
1901  if(mod_num >= max_num) {
1902  exclusion_found = true;
1903  break;
1904  }
1905  }
1906 
1907  if(exclusion_found) {
1908  continue;
1909  }
1910 
1911  bool requirements_done = true;
1912  for(const std::string& s : uniq_require) {
1913  int required_num = std::count(temp_require.begin(), temp_require.end(), s);
1914  int mod_num = modification_count("advancement", s);
1915  if(required_num > mod_num) {
1916  requirements_done = false;
1917  break;
1918  }
1919  }
1920 
1921  if(requirements_done) {
1922  res.push_back(adv);
1923  }
1924  }
1925 
1926  return res;
1927 }
1928 
1929 void unit::set_advancements(std::vector<config> advancements)
1930 {
1932  advancements_ = advancements;
1933 }
1934 
1935 const std::string& unit::type_id() const
1936 {
1937  return type_->id();
1938 }
1939 
1940 void unit::set_big_profile(const std::string& value)
1941 {
1943  profile_ = value;
1945 }
1946 
1947 std::size_t unit::modification_count(const std::string& mod_type, const std::string& id) const
1948 {
1949  std::size_t res = 0;
1950  for(const config& item : modifications_.child_range(mod_type)) {
1951  if(item["id"] == id) {
1952  ++res;
1953  }
1954  }
1955 
1956  // For backwards compatibility, if asked for "advancement", also count "advance"
1957  if(mod_type == "advancement") {
1958  res += modification_count("advance", id);
1959  }
1960 
1961  return res;
1962 }
1963 
1964 const std::set<std::string> unit::builtin_effects {
1965  "alignment", "attack", "defense", "ellipse", "experience", "fearless",
1966  "halo", "healthy", "hitpoints", "image_mod", "jamming", "jamming_costs", "level",
1967  "loyal", "max_attacks", "max_experience", "movement", "movement_costs",
1968  "new_ability", "new_advancement", "new_animation", "new_attack", "overlay", "profile",
1969  "recall_cost", "remove_ability", "remove_advancement", "remove_attacks", "resistance",
1970  "status", "type", "variation", "vision", "vision_costs", "zoc"
1971 };
1972 
1973 std::string unit::describe_builtin_effect(std::string apply_to, const config& effect)
1974 {
1975  if(apply_to == "attack") {
1976  std::vector<t_string> attack_names;
1977 
1978  std::string desc;
1979  for(attack_ptr a : attacks_) {
1980  bool affected = a->describe_modification(effect, &desc);
1981  if(affected && !desc.empty()) {
1982  attack_names.emplace_back(a->name(), "wesnoth-units");
1983  }
1984  }
1985  if(!attack_names.empty()) {
1986  utils::string_map symbols;
1987  symbols["attack_list"] = utils::format_conjunct_list("", attack_names);
1988  symbols["effect_description"] = desc;
1989  return VGETTEXT("$attack_list|: $effect_description", symbols);
1990  }
1991  } else if(apply_to == "hitpoints") {
1992  const std::string& increase_total = effect["increase_total"];
1993  if(!increase_total.empty()) {
1994  return VGETTEXT(
1995  "<span color=\"$color\">$number_or_percent</span> HP",
1996  {{"number_or_percent", utils::print_modifier(increase_total)}, {"color", increase_total[0] == '-' ? "#f00" : "#0f0"}});
1997  }
1998  } else {
1999  const std::string& increase = effect["increase"];
2000  if(increase.empty()) {
2001  return "";
2002  }
2003  if(apply_to == "movement") {
2004  return VNGETTEXT(
2005  "<span color=\"$color\">$number_or_percent</span> move",
2006  "<span color=\"$color\">$number_or_percent</span> moves",
2007  std::stoi(increase),
2008  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "#f00" : "#0f0"}});
2009  } else if(apply_to == "vision") {
2010  return VGETTEXT(
2011  "<span color=\"$color\">$number_or_percent</span> vision",
2012  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "#f00" : "#0f0"}});
2013  } else if(apply_to == "jamming") {
2014  return VGETTEXT(
2015  "<span color=\"$color\">$number_or_percent</span> jamming",
2016  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "#f00" : "#0f0"}});
2017  } else if(apply_to == "max_experience") {
2018  // Unlike others, decreasing experience is a *GOOD* thing
2019  return VGETTEXT(
2020  "<span color=\"$color\">$number_or_percent</span> XP to advance",
2021  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "#0f0" : "#f00"}});
2022  } else if(apply_to == "max_attacks") {
2023  return VNGETTEXT(
2024  "<span color=\"$color\">$number_or_percent</span> attack per turn",
2025  "<span color=\"$color\">$number_or_percent</span> attacks per turn",
2026  std::stoi(increase),
2027  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "#f00" : "#0f0"}});
2028  } else if(apply_to == "recall_cost") {
2029  // Unlike others, decreasing recall cost is a *GOOD* thing
2030  return VGETTEXT(
2031  "<span color=\"$color\">$number_or_percent</span> cost to recall",
2032  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "#0f0" : "#f00"}});
2033  }
2034  }
2035  return "";
2036 }
2037 
2038 void unit::apply_builtin_effect(std::string apply_to, const config& effect)
2039 {
2040  appearance_changed_ = true;
2041  if(apply_to == "fearless") {
2043  is_fearless_ = effect["set"].to_bool(true);
2044  } else if(apply_to == "healthy") {
2046  is_healthy_ = effect["set"].to_bool(true);
2047  } else if(apply_to == "profile") {
2048  if(const config::attribute_value* v = effect.get("portrait")) {
2049  set_big_profile((*v).str());
2050  }
2051 
2052  if(const config::attribute_value* v = effect.get("small_portrait")) {
2053  set_small_profile((*v).str());
2054  }
2055 
2056  if(const config::attribute_value* v = effect.get("description")) {
2057  description_ = *v;
2058  }
2059 
2060  if(config::const_child_itors cfg_range = effect.child_range("special_note")) {
2061  for(const config& c : cfg_range) {
2062  if(!c["remove"].to_bool()) {
2063  special_notes_.emplace_back(c["note"].t_str());
2064  } else {
2065  auto iter = std::find(special_notes_.begin(), special_notes_.end(), c["note"].t_str());
2066  if(iter != special_notes_.end()) {
2067  special_notes_.erase(iter);
2068  }
2069  }
2070  }
2071  }
2072  } else if(apply_to == "new_attack") {
2074  attacks_.emplace_back(new attack_type(effect));
2075  } else if(apply_to == "remove_attacks") {
2077  auto iter = std::remove_if(attacks_.begin(), attacks_.end(), [&effect](attack_ptr a) {
2078  return a->matches_filter(effect);
2079  });
2080 
2081  attacks_.erase(iter, attacks_.end());
2082  } else if(apply_to == "attack") {
2084  for(attack_ptr a : attacks_) {
2085  a->apply_modification(effect);
2086  }
2087  } else if(apply_to == "hitpoints") {
2088  LOG_UT << "applying hitpoint mod..." << hit_points_ << "/" << max_hit_points_;
2089  const std::string& increase_hp = effect["increase"];
2090  const std::string& increase_total = effect["increase_total"];
2091  const std::string& set_hp = effect["set"];
2092  const std::string& set_total = effect["set_total"];
2093 
2094  // If the hitpoints are allowed to end up greater than max hitpoints
2095  const bool violate_max = effect["violate_maximum"].to_bool();
2096 
2097  if(!set_hp.empty()) {
2098  if(set_hp.back() == '%') {
2099  hit_points_ = lexical_cast_default<int>(set_hp)*max_hit_points_/100;
2100  } else {
2101  hit_points_ = lexical_cast_default<int>(set_hp);
2102  }
2103  }
2104 
2105  if(!set_total.empty()) {
2106  if(set_total.back() == '%') {
2107  set_max_hitpoints(lexical_cast_default<int>(set_total)*max_hit_points_/100);
2108  } else {
2109  set_max_hitpoints(lexical_cast_default<int>(set_total));
2110  }
2111  }
2112 
2113  if(!increase_total.empty()) {
2114  // A percentage on the end means increase by that many percent
2116  }
2117 
2118  if(max_hit_points_ < 1)
2119  set_max_hitpoints(1);
2120 
2121  if(effect["heal_full"].to_bool()) {
2122  heal_fully();
2123  }
2124 
2125  if(!increase_hp.empty()) {
2127  }
2128 
2129  LOG_UT << "modded to " << hit_points_ << "/" << max_hit_points_;
2130  if(hit_points_ > max_hit_points_ && !violate_max) {
2131  LOG_UT << "resetting hp to max";
2133  }
2134 
2135  if(hit_points_ < 1) {
2136  hit_points_ = 1;
2137  }
2138  } else if(apply_to == "movement") {
2139  const bool apply_to_vision = effect["apply_to_vision"].to_bool(true);
2140 
2141  // Unlink vision from movement, regardless of whether we'll increment both or not
2142  if(vision_ < 0) {
2144  }
2145 
2146  const int old_max = max_movement_;
2147 
2148  const std::string& increase = effect["increase"];
2149  if(!increase.empty()) {
2151  }
2152 
2153  set_total_movement(effect["set"].to_int(max_movement_));
2154 
2155  if(movement_ > max_movement_) {
2157  }
2158 
2159  if(apply_to_vision) {
2160  vision_ = std::max(0, vision_ + max_movement_ - old_max);
2161  }
2162  } else if(apply_to == "vision") {
2163  // Unlink vision from movement, regardless of which one we're about to change.
2164  if(vision_ < 0) {
2166  }
2167 
2168  const std::string& increase = effect["increase"];
2169  if(!increase.empty()) {
2170  vision_ = utils::apply_modifier(vision_, increase, 1);
2171  }
2172 
2173  vision_ = effect["set"].to_int(vision_);
2174  } else if(apply_to == "jamming") {
2175  const std::string& increase = effect["increase"];
2176 
2177  if(!increase.empty()) {
2178  jamming_ = utils::apply_modifier(jamming_, increase, 1);
2179  }
2180 
2181  jamming_ = effect["set"].to_int(jamming_);
2182  } else if(apply_to == "experience") {
2183  const std::string& increase = effect["increase"];
2184  const std::string& set = effect["set"];
2185 
2186  if(!set.empty()) {
2187  if(set.back() == '%') {
2188  experience_ = lexical_cast_default<int>(set)*max_experience_/100;
2189  } else {
2190  experience_ = lexical_cast_default<int>(set);
2191  }
2192  }
2193 
2194  if(increase.empty() == false) {
2196  }
2197  } else if(apply_to == "max_experience") {
2198  const std::string& increase = effect["increase"];
2199  const std::string& set = effect["set"];
2200 
2201  if(set.empty() == false) {
2202  if(set.back() == '%') {
2203  set_max_experience(lexical_cast_default<int>(set)*max_experience_/100);
2204  } else {
2205  set_max_experience(lexical_cast_default<int>(set));
2206  }
2207  }
2208 
2209  if(increase.empty() == false) {
2211  }
2212  } else if(apply_to == upkeep_loyal::type()) {
2213  upkeep_ = upkeep_loyal{};
2214  } else if(apply_to == "status") {
2215  const std::string& add = effect["add"];
2216  const std::string& remove = effect["remove"];
2217 
2218  for(const std::string& to_add : utils::split(add))
2219  {
2220  set_state(to_add, true);
2221  }
2222 
2223  for(const std::string& to_remove : utils::split(remove))
2224  {
2225  set_state(to_remove, false);
2226  }
2227  } else if(std::find(movetype::effects.cbegin(), movetype::effects.cend(), apply_to) != movetype::effects.cend()) {
2228  // "movement_costs", "vision_costs", "jamming_costs", "defense", "resistance"
2229  if(auto ap = effect.optional_child(apply_to)) {
2231  movement_type_.merge(*ap, apply_to, effect["replace"].to_bool());
2232  }
2233  } else if(apply_to == "zoc") {
2234  if(const config::attribute_value* v = effect.get("value")) {
2236  emit_zoc_ = v->to_bool();
2237  }
2238  } else if(apply_to == "new_ability") {
2239  if(auto ab_effect = effect.optional_child("abilities")) {
2241  config to_append;
2242  for(const config::any_child ab : ab_effect->all_children_range()) {
2243  if(!has_ability_by_id(ab.cfg["id"])) {
2244  to_append.add_child(ab.key, ab.cfg);
2245  }
2246  }
2247  abilities_.append(to_append);
2248  }
2249  } else if(apply_to == "remove_ability") {
2250  if(auto ab_effect = effect.optional_child("abilities")) {
2251  deprecated_message("[effect]apply_to=remove_ability [abilities]", DEP_LEVEL::INDEFINITE, "", "Use [filter_ability] instead in [effect]apply_to=remove_ability");
2252  for(const config::any_child ab : ab_effect->all_children_range()) {
2253  remove_ability_by_id(ab.cfg["id"]);
2254  }
2255  }
2256  if(auto fab_effect = effect.optional_child("filter_ability")) {
2257  remove_ability_by_attribute(*fab_effect);
2258  }
2259  } else if(apply_to == "image_mod") {
2260  LOG_UT << "applying image_mod";
2261  std::string mod = effect["replace"];
2262  if(!mod.empty()){
2263  image_mods_ = mod;
2264  }
2265  LOG_UT << "applying image_mod";
2266  mod = effect["add"].str();
2267  if(!mod.empty()){
2268  if(!image_mods_.empty()) {
2269  image_mods_ += '~';
2270  }
2271 
2272  image_mods_ += mod;
2273  }
2274 
2276  LOG_UT << "applying image_mod";
2277  } else if(apply_to == "new_animation") {
2278  anim_comp_->apply_new_animation_effect(effect);
2279  } else if(apply_to == "ellipse") {
2280  set_image_ellipse(effect["ellipse"]);
2281  } else if(apply_to == "halo") {
2282  set_image_halo(effect["halo"]);
2283  } else if(apply_to == "overlay") {
2284  const std::string& add = effect["add"];
2285  const std::string& replace = effect["replace"];
2286  const std::string& remove = effect["remove"];
2287 
2288  if(!add.empty()) {
2289  for(const auto& to_add : utils::parenthetical_split(add, ',')) {
2290  overlays_.push_back(to_add);
2291  }
2292  }
2293  if(!remove.empty()) {
2294  for(const auto& to_remove : utils::parenthetical_split(remove, ',')) {
2295  overlays_.erase(std::remove(overlays_.begin(), overlays_.end(), to_remove), overlays_.end());
2296  }
2297  }
2298  if(add.empty() && remove.empty() && !replace.empty()) {
2299  overlays_ = utils::parenthetical_split(replace, ',');
2300  }
2301  } else if(apply_to == "new_advancement") {
2302  const std::string& types = effect["types"];
2303  const bool replace = effect["replace"].to_bool(false);
2305 
2306  if(!types.empty()) {
2307  if(replace) {
2309  } else {
2310  std::vector<std::string> temp_advances = utils::parenthetical_split(types, ',');
2311  std::copy(temp_advances.begin(), temp_advances.end(), std::back_inserter(advances_to_));
2312  }
2313  }
2314 
2315  if(effect.has_child("advancement")) {
2316  if(replace) {
2317  advancements_.clear();
2318  }
2319 
2320  for(const config& adv : effect.child_range("advancement")) {
2321  advancements_.push_back(adv);
2322  }
2323  }
2324  } else if(apply_to == "remove_advancement") {
2325  const std::string& types = effect["types"];
2326  const std::string& amlas = effect["amlas"];
2328 
2329  std::vector<std::string> temp_advances = utils::parenthetical_split(types, ',');
2331  for(const std::string& unit : temp_advances) {
2332  iter = std::find(advances_to_.begin(), advances_to_.end(), unit);
2333  if(iter != advances_to_.end()) {
2334  advances_to_.erase(iter);
2335  }
2336  }
2337 
2338  temp_advances = utils::parenthetical_split(amlas, ',');
2339 
2340  for(int i = advancements_.size() - 1; i >= 0; i--) {
2341  if(std::find(temp_advances.begin(), temp_advances.end(), advancements_[i]["id"]) != temp_advances.end()) {
2342  advancements_.erase(advancements_.begin() + i);
2343  }
2344  }
2345  } else if(apply_to == "alignment") {
2346  auto new_align = unit_alignments::get_enum(effect["set"].str());
2347  if(new_align) {
2348  set_alignment(*new_align);
2349  }
2350  } else if(apply_to == "max_attacks") {
2351  const std::string& increase = effect["increase"];
2352 
2353  if(!increase.empty()) {
2355  }
2356  } else if(apply_to == "recall_cost") {
2357  const std::string& increase = effect["increase"];
2358  const std::string& set = effect["set"];
2359  const int team_recall_cost = resources::gameboard ? resources::gameboard->get_team(side_).recall_cost() : 20;
2360  const int recall_cost = recall_cost_ < 0 ? team_recall_cost : recall_cost_;
2361 
2362  if(!set.empty()) {
2363  if(set.back() == '%') {
2364  recall_cost_ = lexical_cast_default<int>(set)*recall_cost/100;
2365  } else {
2366  recall_cost_ = lexical_cast_default<int>(set);
2367  }
2368  }
2369 
2370  if(!increase.empty()) {
2372  }
2373  } else if(effect["apply_to"] == "variation") {
2374  const unit_type* base_type = unit_types.find(type().parent_id());
2375  assert(base_type != nullptr);
2376  const std::string& variation_id = effect["name"];
2377  if(variation_id.empty() || base_type->get_gender_unit_type(gender_).has_variation(variation_id)) {
2378  variation_ = variation_id;
2379  advance_to(*base_type);
2380  if(effect["heal_full"].to_bool(false)) {
2381  heal_fully();
2382  }
2383  } else {
2384  WRN_UT << "unknown variation '" << variation_id << "' (name=) in [effect]apply_to=variation, ignoring";
2385  }
2386  } else if(effect["apply_to"] == "type") {
2387  std::string prev_type = effect["prev_type"];
2388  if(prev_type.empty()) {
2389  prev_type = type().parent_id();
2390  }
2391  const std::string& new_type_id = effect["name"];
2392  const unit_type* new_type = unit_types.find(new_type_id);
2393  if(new_type) {
2394  advance_to(*new_type);
2395  preferences::encountered_units().insert(new_type_id);
2396  if(effect["heal_full"].to_bool(false)) {
2397  heal_fully();
2398  }
2399  } else {
2400  WRN_UT << "unknown type '" << new_type_id << "' (name=) in [effect]apply_to=type, ignoring";
2401  }
2402  } else if(effect["apply_to"] == "level") {
2403  const std::string& increase = effect["increase"];
2404  const std::string& set = effect["set"];
2405 
2407 
2408  // no support for percentages, since levels are usually small numbers
2409 
2410  if(!set.empty()) {
2411  level_ = lexical_cast_default<int>(set);
2412  }
2413 
2414  if(!increase.empty()) {
2415  level_ += lexical_cast_default<int>(increase);
2416  }
2417  }
2418 }
2419 
2420 void unit::add_modification(const std::string& mod_type, const config& mod, bool no_add)
2421 {
2422  bool generate_description = mod["generate_description"].to_bool(true);
2423 
2424  if(no_add == false) {
2425  modifications_.add_child(mod_type, mod);
2426  }
2427 
2428  bool set_poisoned = false; // Tracks if the poisoned state was set after the type or variation was changed.
2429  config type_effect, variation_effect;
2430  std::vector<t_string> effects_description;
2431  for(const config& effect : mod.child_range("effect")) {
2432  // Apply SUF.
2433  if(auto afilter = effect.optional_child("filter")) {
2434  assert(resources::filter_con);
2435  if(!unit_filter(vconfig(*afilter)).matches(*this, loc_)) {
2436  continue;
2437  }
2438  }
2439  const std::string& apply_to = effect["apply_to"];
2440  int times = effect["times"].to_int(1);
2441  t_string description;
2442 
2443  if(effect["times"] == "per level") {
2444  if(effect["apply_to"] == "level") {
2445  WRN_UT << "[effect] times=per level is not allowed with apply_to=level, using default value of 1";
2446  times = 1;
2447  }
2448  else {
2449  times = level_;
2450  }
2451  }
2452 
2453  if(times) {
2454  while (times > 0) {
2455  times --;
2456 
2457  bool was_poisoned = get_state(STATE_POISONED);
2458  // Apply unit type/variation changes last to avoid double applying effects on advance.
2459  if(apply_to == "type") {
2460  set_poisoned = false;
2461  type_effect = effect;
2462  continue;
2463  }
2464  if(apply_to == "variation") {
2465  set_poisoned = false;
2466  variation_effect = effect;
2467  continue;
2468  }
2469 
2470  std::string description_component;
2471  if(resources::lua_kernel) {
2472  description_component = resources::lua_kernel->apply_effect(apply_to, *this, effect, true);
2473  } else if(builtin_effects.count(apply_to)) {
2474  // Normally, the built-in effects are dispatched through Lua so that a user
2475  // can override them if desired. However, since they're built-in, we can still
2476  // apply them if the lua kernel is unavailable.
2477  apply_builtin_effect(apply_to, effect);
2478  description_component = describe_builtin_effect(apply_to, effect);
2479  }
2480  if(!times) {
2481  description += description_component;
2482  }
2483  if(!was_poisoned && get_state(STATE_POISONED)) {
2484  set_poisoned = true;
2485  } else if(was_poisoned && !get_state(STATE_POISONED)) {
2486  set_poisoned = false;
2487  }
2488  } // end while
2489  } else { // for times = per level & level = 0 we still need to rebuild the descriptions
2490  if(resources::lua_kernel) {
2491  description += resources::lua_kernel->apply_effect(apply_to, *this, effect, false);
2492  } else if(builtin_effects.count(apply_to)) {
2493  description += describe_builtin_effect(apply_to, effect);
2494  }
2495  }
2496 
2497  if(effect["times"] == "per level" && !times) {
2498  description = VGETTEXT("$effect_description per level", {{"effect_description", description}});
2499  }
2500 
2501  if(!description.empty()) {
2502  effects_description.push_back(description);
2503  }
2504  }
2505  // Apply variations -- only apply if we are adding this for the first time.
2506  if((!type_effect.empty() || !variation_effect.empty()) && no_add == false) {
2507  if(!type_effect.empty()) {
2508  std::string description;
2509  if(resources::lua_kernel) {
2510  description = resources::lua_kernel->apply_effect(type_effect["apply_to"], *this, type_effect, true);
2511  } else if(builtin_effects.count(type_effect["apply_to"])) {
2512  apply_builtin_effect(type_effect["apply_to"], type_effect);
2513  description = describe_builtin_effect(type_effect["apply_to"], type_effect);
2514  }
2515  effects_description.push_back(description);
2516  }
2517  if(!variation_effect.empty()) {
2518  std::string description;
2519  if(resources::lua_kernel) {
2520  description = resources::lua_kernel->apply_effect(variation_effect["apply_to"], *this, variation_effect, true);
2521  } else if(builtin_effects.count(variation_effect["apply_to"])) {
2522  apply_builtin_effect(variation_effect["apply_to"], variation_effect);
2523  description = describe_builtin_effect(variation_effect["apply_to"], variation_effect);
2524  }
2525  effects_description.push_back(description);
2526  }
2527  if(set_poisoned)
2528  // An effect explicitly set the poisoned state, and this
2529  // should override the unit being immune to poison.
2530  set_state(STATE_POISONED, true);
2531  }
2532 
2533  t_string description;
2534 
2535  const t_string& mod_description = mod["description"];
2536  if(!mod_description.empty()) {
2537  description = mod_description;
2538  }
2539 
2540  // Punctuation should be translatable: not all languages use Latin punctuation.
2541  // (However, there maybe is a better way to do it)
2542  if(generate_description && !effects_description.empty()) {
2543  if(!mod_description.empty()) {
2544  description += "\n";
2545  }
2546 
2547  for(const auto& desc_line : effects_description) {
2548  description += desc_line + "\n";
2549  }
2550  }
2551 
2552  // store trait info
2553  if(mod_type == "trait") {
2554  add_trait_description(mod, description);
2555  }
2556 
2557  //NOTE: if not a trait, description is currently not used
2558 }
2559 
2560 void unit::add_trait_description(const config& trait, const t_string& description)
2561 {
2562  const std::string& gender_string = gender_ == unit_race::FEMALE ? "female_name" : "male_name";
2563  const auto& gender_specific_name = trait[gender_string];
2564 
2565  const t_string name = gender_specific_name.empty() ? trait["name"] : gender_specific_name;
2566 
2567  if(!name.empty()) {
2568  trait_names_.push_back(name);
2569  trait_descriptions_.push_back(description);
2570  }
2571 }
2572 
2573 std::string unit::absolute_image() const
2574 {
2575  return type().icon().empty() ? type().image() : type().icon();
2576 }
2577 
2578 std::string unit::default_anim_image() const
2579 {
2580  return type().image().empty() ? type().icon() : type().image();
2581 }
2582 
2584 {
2585  log_scope("apply mods");
2586 
2587  variables_.clear_children("mods");
2588  if(modifications_.has_child("advance")) {
2589  deprecated_message("[advance]", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use [advancement] instead.");
2590  }
2592  add_modification(mod.key, mod.cfg, true);
2593  }
2594 }
2595 
2596 bool unit::invisible(const map_location& loc, bool see_all) const
2597 {
2598  if(loc != get_location()) {
2599  DBG_UT << "unit::invisible called: id = " << id() << " loc = " << loc << " get_loc = " << get_location();
2600  }
2601 
2602  // This is a quick condition to check, and it does not depend on the
2603  // location (so might as well bypass the location-based cache).
2604  if(get_state(STATE_UNCOVERED)) {
2605  return false;
2606  }
2607 
2608  // Fetch from cache
2609  /**
2610  * @todo FIXME: We use the cache only when using the default see_all=true
2611  * Maybe add a second cache if the see_all=false become more frequent.
2612  */
2613  if(see_all) {
2614  const auto itor = invisibility_cache_.find(loc);
2615  if(itor != invisibility_cache_.end()) {
2616  return itor->second;
2617  }
2618  }
2619 
2620  // Test hidden status
2621  static const std::string hides("hides");
2622  bool is_inv = get_ability_bool(hides, loc);
2623  if(is_inv){
2624  is_inv = (resources::gameboard ? !resources::gameboard->would_be_discovered(loc, side_,see_all) : true);
2625  }
2626 
2627  if(see_all) {
2628  // Add to caches
2629  if(invisibility_cache_.empty()) {
2630  units_with_cache.push_back(this);
2631  }
2632 
2633  invisibility_cache_[loc] = is_inv;
2634  }
2635 
2636  return is_inv;
2637 }
2638 
2639 bool unit::is_visible_to_team(const team& team, bool const see_all) const
2640 {
2641  const map_location& loc = get_location();
2642  return is_visible_to_team(loc, team, see_all);
2643 }
2644 
2645 bool unit::is_visible_to_team(const map_location& loc, const team& team, bool const see_all) const
2646 {
2647  if(!display::get_singleton()->get_map().on_board(loc)) {
2648  return false;
2649  }
2650 
2651  if(see_all) {
2652  return true;
2653  }
2654 
2655  if(team.is_enemy(side()) && invisible(loc)) {
2656  return false;
2657  }
2658 
2659  // allied planned moves are also visible under fog. (we assume that fake units on the map are always whiteboard markers)
2660  if(!team.is_enemy(side()) && underlying_id_.is_fake()) {
2661  return true;
2662  }
2663 
2664  // when the whiteboard planned unit map is applied, it uses moved the _real_ unit so
2665  // underlying_id_.is_fake() will be false and the check above will not apply.
2666  // TODO: improve this check so that is also works for allied planned units but without
2667  // breaking sp campaigns with allies under fog. We probably need an explicit flag
2668  // is_planned_ in unit that is set by the whiteboard.
2669  if(team.side() == side()) {
2670  return true;
2671  }
2672 
2673  if(team.fogged(loc)) {
2674  return false;
2675  }
2676 
2677  return true;
2678 }
2679 
2681 {
2682  if(underlying_id_.value == 0) {
2684  underlying_id_ = id_manager.next_id();
2685  } else {
2686  underlying_id_ = id_manager.next_fake_id();
2687  }
2688  }
2689 
2690  if(id_.empty() /*&& !underlying_id_.is_fake()*/) {
2691  std::stringstream ss;
2692  ss << (type_id().empty() ? "Unit" : type_id()) << "-" << underlying_id_.value;
2693  id_ = ss.str();
2694  }
2695 }
2696 
2697 unit& unit::mark_clone(bool is_temporary)
2698 {
2700  if(is_temporary) {
2701  underlying_id_ = ids.next_fake_id();
2702  } else {
2704  underlying_id_ = ids.next_id();
2705  }
2706  else {
2707  underlying_id_ = ids.next_fake_id();
2708  }
2709  std::string::size_type pos = id_.find_last_of('-');
2710  if(pos != std::string::npos && pos+1 < id_.size()
2711  && id_.find_first_not_of("0123456789", pos+1) == std::string::npos) {
2712  // this appears to be a duplicate of a generic unit, so give it a new id
2713  WRN_UT << "assigning new id to clone of generic unit " << id_;
2714  id_.clear();
2715  set_underlying_id(ids);
2716  }
2717  }
2718  return *this;
2719 }
2720 
2721 
2723  : u_(const_cast<unit&>(u))
2724  , moves_(u.movement_left(true))
2725 {
2726  if(operate) {
2728  }
2729 }
2730 
2732 {
2733  assert(resources::gameboard);
2734  try {
2735  if(!resources::gameboard->units().has_unit(&u_)) {
2736  /*
2737  * It might be valid that the unit is not in the unit map.
2738  * It might also mean a no longer valid unit will be assigned to.
2739  */
2740  DBG_UT << "The unit to be removed is not in the unit map.";
2741  }
2742 
2744  } catch(...) {
2745  DBG_UT << "Caught exception when destroying unit_movement_resetter: " << utils::get_unknown_exception_type();
2746  }
2747 }
2748 
2749 std::string unit::TC_image_mods() const
2750 {
2751  return formatter() << "~RC(" << flag_rgb() << ">" << team::get_side_color_id(side()) << ")";
2752 }
2753 
2754 std::string unit::image_mods() const
2755 {
2756  if(!image_mods_.empty()) {
2757  return formatter() << "~" << image_mods_ << TC_image_mods();
2758  }
2759 
2760  return TC_image_mods();
2761 }
2762 
2763 // Called by the Lua API after resetting an attack pointer.
2765 {
2767  auto iter = std::find(attacks_.begin(), attacks_.end(), atk);
2768  if(iter == attacks_.end()) {
2769  return false;
2770  }
2771  attacks_.erase(iter);
2772  return true;
2773 }
2774 
2776 {
2777  if(attacks_left_ == max_attacks_) {
2778  //TODO: add state_not_attacked
2779  }
2780 
2781  set_attacks(0);
2782 }
2783 
2785 {
2786  if(movement_left() == total_movement()) {
2787  set_state(STATE_NOT_MOVED,true);
2788  }
2789 
2790  set_movement(0, true);
2791 }
2792 
2793 void unit::set_hidden(bool state) const
2794 {
2795 // appearance_changed_ = true;
2796  hidden_ = state;
2797  if(!state) {
2798  return;
2799  }
2800 
2801  // TODO: this should really hide the halo, not destroy it
2802  // We need to get rid of haloes immediately to avoid display glitches
2803  anim_comp_->clear_haloes();
2804 }
2805 
2806 void unit::set_image_halo(const std::string& halo)
2807 {
2808  appearance_changed_ = true;
2809  anim_comp_->clear_haloes();
2810  halo_ = halo;
2811 }
2812 
2814 {
2815  if(upkeep.empty()) {
2816  return;
2817  }
2818 
2819  try {
2820  upkeep_ = upkeep.apply_visitor(upkeep_parser_visitor{});
2821  } catch(std::invalid_argument& e) {
2822  WRN_UT << "Found invalid upkeep=\"" << e.what() << "\" in a unit";
2823  upkeep_ = upkeep_full{};
2824  }
2825 }
2826 
2828 {
2829  upkeep = utils::visit(upkeep_type_visitor{}, upkeep_);
2830 }
2831 
2833 {
2834  changed_attributes_.reset();
2835  for(const auto& a_ptr : attacks_) {
2836  a_ptr->set_changed(false);
2837  }
2838 }
2839 
2840 std::vector<t_string> unit::unit_special_notes() const {
2842 }
2843 
2844 // Filters unimportant stats from the unit config and returns a checksum of
2845 // the remaining config.
2847 {
2848  config unit_config;
2849  config wcfg;
2850  u.write(unit_config);
2851 
2852  static const std::set<std::string_view> main_keys {
2853  "advances_to",
2854  "alignment",
2855  "cost",
2856  "experience",
2857  "gender",
2858  "hitpoints",
2859  "ignore_race_traits",
2860  "ignore_global_traits",
2861  "level",
2862  "recall_cost",
2863  "max_attacks",
2864  "max_experience",
2865  "max_hitpoints",
2866  "max_moves",
2867  "movement",
2868  "movement_type",
2869  "race",
2870  "random_traits",
2871  "resting",
2872  "undead_variation",
2873  "upkeep",
2874  "zoc"
2875  };
2876 
2877  for(const std::string_view& main_key : main_keys) {
2878  wcfg[main_key] = unit_config[main_key];
2879  }
2880 
2881  static const std::set<std::string_view> attack_keys {
2882  "name",
2883  "type",
2884  "range",
2885  "damage",
2886  "number"
2887  };
2888 
2889  for(const config& att : unit_config.child_range("attack")) {
2890  config& child = wcfg.add_child("attack");
2891 
2892  for(const std::string_view& attack_key : attack_keys) {
2893  child[attack_key] = att[attack_key];
2894  }
2895 
2896  for(const config& spec : att.child_range("specials")) {
2897  config& child_spec = child.add_child("specials", spec);
2898 
2899  child_spec.recursive_clear_value("description");
2901  child_spec.recursive_clear_value("description_inactive");
2902  child_spec.recursive_clear_value("name");
2903  child_spec.recursive_clear_value("name_inactive");
2904  }
2905  }
2906  }
2907 
2908  for(const config& abi : unit_config.child_range("abilities")) {
2909  config& child = wcfg.add_child("abilities", abi);
2910 
2911  child.recursive_clear_value("description");
2912  child.recursive_clear_value("description_inactive");
2913  child.recursive_clear_value("name");
2914  child.recursive_clear_value("name_inactive");
2915  }
2916 
2917  for(const config& trait : unit_config.child_range("trait")) {
2918  config& child = wcfg.add_child("trait", trait);
2919 
2920  child.recursive_clear_value("description");
2921  child.recursive_clear_value("male_name");
2922  child.recursive_clear_value("female_name");
2923  child.recursive_clear_value("name");
2924  }
2925 
2926  static const std::set<std::string_view> child_keys {
2927  "advance_from",
2928  "defense",
2929  "movement_costs",
2930  "vision_costs",
2931  "jamming_costs",
2932  "resistance"
2933  };
2934 
2935  for(const std::string_view& child_key : child_keys) {
2936  for(const config& c : unit_config.child_range(child_key)) {
2937  wcfg.add_child(child_key, c);
2938  }
2939  }
2940 
2941  DBG_UT << wcfg;
2942 
2943  return wcfg.hash();
2944 }
const map_location goto_
Definition: move.cpp:312
Managing the AIs lifecycle - headers TODO: Refactor history handling and internal commands.
double t
Definition: astarsearch.cpp:65
void append_active_ai_for_side(ai::side_number side, const config &cfg)
Appends AI parameters to active AI of the given side.
Definition: manager.cpp:672
static manager & get_singleton()
Definition: manager.hpp:145
Variant for storing WML attributes.
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:161
void append(const config &cfg)
Append data from another config object to this one.
Definition: config.cpp:208
all_children_iterator erase(const all_children_iterator &i)
Definition: config.cpp:644
const_all_children_iterator ordered_begin() const
Definition: config.cpp:871
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:399
config & mandatory_child(config_key_type key, int n=0)
Returns the nth child with the given key, or throws an error if there is none.
Definition: config.cpp:371
void recursive_clear_value(config_key_type key)
Definition: config.cpp:609
void remove_child(config_key_type key, std::size_t index)
Definition: config.cpp:649
const_attr_itors attribute_range() const
Definition: config.cpp:767
std::size_t child_count(config_key_type key) const
Definition: config.cpp:301
const_all_children_iterator ordered_end() const
Definition: config.cpp:881
void clear_children(T... keys)
Definition: config.hpp:644
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:321
bool has_attribute(config_key_type key) const
Definition: config.cpp:159
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:891
child_itors child_range(config_key_type key)
Definition: config.cpp:277
boost::iterator_range< const_attribute_iterator > const_attr_itors
Definition: config.hpp:361
std::size_t all_children_count() const
Definition: config.cpp:311
attribute_map::value_type attribute
Definition: config.hpp:301
boost::iterator_range< const_child_iterator > const_child_itors
Definition: config.hpp:285
void append_children(const config &cfg)
Adds children from cfg.
Definition: config.cpp:169
bool empty() const
Definition: config.cpp:856
void clear()
Definition: config.cpp:835
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:691
std::string hash() const
Definition: config.cpp:1291
optional_config_impl< config > optional_child(config_key_type key, int n=0)
Euivalent to mandatory_child, but returns an empty optional if the nth child was not found.
Definition: config.cpp:389
config & add_child(config_key_type key)
Definition: config.cpp:445
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 display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:101
std::ostringstream wrapper.
Definition: formatter.hpp:40
team & get_team(int i)
Definition: game_board.hpp:98
n_unit::id_manager & unit_id_manager()
Definition: game_board.hpp:80
static game_config_view wrap(const config &cfg)
@ INITIAL
creating intitial [unit]s, executing toplevel [lua] etc.
Definition: game_data.hpp:74
void add_events(const config::const_child_itors &cfgs, game_lua_kernel &lk, const std::string &type=std::string())
Definition: manager.cpp:155
std::string apply_effect(const std::string &name, unit &u, const config &cfg, bool need_apply)
void write(config &cfg, bool include_notes) const
Writes the movement type data to the provided config.
Definition: movetype.cpp:915
static const std::set< std::string > effects
The set of applicable effects for movement types.
Definition: movetype.hpp:347
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:871
int defense_modifier(const t_translation::terrain_code &terrain) const
Returns the defensive value of the indicated terrain.
Definition: movetype.hpp:292
int resistance_against(const attack_type &attack) const
Returns the resistance against the indicated attack.
Definition: movetype.hpp:296
static id_manager & global_instance()
Definition: id.hpp:61
unit_id next_fake_id()
Definition: id.cpp:35
unit_id next_id()
returns id for unit that is created
Definition: id.cpp:28
static rng & default_instance()
Definition: random.cpp:74
int get_random_int(int min, int max)
Definition: random.hpp:52
static bool is_synced()
bool empty() const
Definition: tstring.hpp:187
This class stores all the data for a single 'side' (in game nomenclature).
Definition: team.hpp:76
int side() const
Definition: team.hpp:176
int recall_cost() const
Definition: team.hpp:181
bool is_enemy(int n) const
Definition: team.hpp:231
static std::string get_side_color_id(unsigned side)
Definition: team.cpp:972
bool fogged(const map_location &loc) const
Definition: team.cpp:660
Visitor helper class to parse the upkeep value from a config.
Definition: unit.hpp:1195
Visitor helper class to fetch the appropriate upkeep value.
Definition: unit.hpp:1145
int get_composite_value() const
Definition: abilities.hpp:47
std::pair< int, map_location > highest(const std::string &key, int def=0) const
Definition: unit.hpp:70
bool empty() const
Definition: unit.hpp:92
const std::string & id() const
Definition: race.hpp:35
static const unit_race null_race
Dummy race used when a race is not yet known.
Definition: race.hpp:69
std::string generate_name(GENDER gender) const
Definition: race.cpp:114
@ NUM_GENDERS
Definition: race.hpp:27
@ FEMALE
Definition: race.hpp:27
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:1246
const unit_race * find_race(const std::string &) const
Definition: types.cpp:1350
void check_types(const std::vector< std::string > &types) const
Definition: types.cpp:1267
A single unit type that the player may recruit.
Definition: types.hpp:46
std::vector< t_string > direct_special_notes() const
Returns only the notes defined by [unit_type][special_note] tags, excluding any that would be found f...
Definition: types.hpp:158
const std::string & parent_id() const
The id of the original type from which this (variation) descended.
Definition: types.hpp:148
const std::string & image() const
Definition: types.hpp:179
config::const_child_itors advancements() const
Definition: types.hpp:239
const std::string & variation_id() const
The id of this variation; empty if it's a gender variation or a base unit.
Definition: types.hpp:150
const std::string & id() const
The id for this unit_type.
Definition: types.hpp:144
const movetype & movement_type() const
Definition: types.hpp:191
std::string halo() const
Definition: types.hpp:183
const unit_race * race() const
Never returns nullptr, but may point to the null race.
Definition: types.hpp:279
int hitpoints() const
Definition: types.hpp:164
double xp_bar_scaling() const
Definition: types.hpp:166
const std::string & default_variation() const
Definition: types.hpp:176
const unit_type & get_variation(const std::string &id) const
Definition: types.cpp:474
const_attack_itors attacks() const
Definition: types.cpp:543
const std::string & usage() const
Definition: types.hpp:178
config::const_child_itors events() const
Definition: types.hpp:242
const std::vector< std::string > & advances_to() const
A vector of unit_type ids that this unit_type can advance to.
Definition: types.hpp:118
bool has_variation(const std::string &variation_id) const
Definition: types.cpp:757
std::string ellipse() const
Definition: types.hpp:184
int movement() const
Definition: types.hpp:169
t_string unit_description() const
Definition: types.cpp:484
static void check_id(std::string &id)
Validate the id argument.
Definition: types.cpp:1439
int max_attacks() const
Definition: types.hpp:174
const std::string & flag_rgb() const
Definition: types.cpp:720
int vision() const
Definition: types.hpp:170
const config & abilities_cfg() const
Definition: types.hpp:236
unit_type_error error
Definition: types.hpp:52
int cost() const
Definition: types.hpp:175
const std::string log_id() const
A variant on id() that is more descriptive, for use with message logging.
Definition: types.hpp:146
const unit_type & get_gender_unit_type(std::string gender) const
Returns a gendered variant of this unit_type.
Definition: types.cpp:453
const std::string & icon() const
Definition: types.hpp:180
int experience_needed(bool with_acceleration=true) const
Definition: types.cpp:577
bool generate_name() const
Definition: types.hpp:185
const std::string & big_profile() const
Definition: types.hpp:182
const std::string & undead_variation() const
Info on the type of unit that the unit reanimates as.
Definition: types.hpp:136
double hp_bar_scaling() const
Definition: types.hpp:165
const t_string & type_name() const
The name of the unit in the current language setting.
Definition: types.hpp:141
config::const_child_itors possible_traits() const
Definition: types.hpp:233
int level() const
Definition: types.hpp:167
bool has_zoc() const
Definition: types.hpp:228
unit_alignments::type alignment() const
Definition: types.hpp:195
const std::string & small_profile() const
Definition: types.hpp:181
const config & get_cfg() const
Definition: types.hpp:283
unsigned int num_traits() const
Definition: types.hpp:138
int recall_cost() const
Definition: types.hpp:168
int jamming() const
Definition: types.hpp:173
This class represents a single unit of a specific type.
Definition: unit.hpp:134
static void clear_status_caches()
Clear this unit status cache for all units.
Definition: unit.cpp:679
void set_attr_changed(UNIT_ATTRIBUTE attr)
Definition: unit.hpp:186
virtual ~unit()
Definition: unit.cpp:713
bool get_attr_changed(UNIT_ATTRIBUTE attr) const
Definition: unit.hpp:193
void clear_changed_attributes()
Definition: unit.cpp:2832
void init(const config &cfg, bool use_traits=false, const vconfig *vcfg=nullptr)
Definition: unit.cpp:382
static const std::string & leader_crown()
The path to the leader crown overlay.
Definition: unit.cpp:1051
bool get_attacks_changed() const
Definition: unit.cpp:1544
unit()=delete
A variable-expanding proxy for the config class.
Definition: variable.hpp:45
std::vector< vconfig > child_list
Definition: variable.hpp:78
bool null() const
Definition: variable.hpp:72
vconfig child(const std::string &key) const
Returns a child of *this whose key is key.
Definition: variable.cpp:288
const config & get_config() const
Definition: variable.hpp:75
child_list get_children(const std::string &key) const
Definition: variable.cpp:226
std::string deprecated_message(const std::string &elem_name, DEP_LEVEL level, const version_info &version, const std::string &detail)
Definition: deprecation.cpp:30
#define VGETTEXT(msgid,...)
Handy wrappers around interpolate_variables_into_string and gettext.
#define VNGETTEXT(msgid, msgid_plural, count,...)
std::size_t i
Definition: function.cpp:968
map_location loc_
Interfaces for manipulating version numbers of engine, add-ons, etc.
int hit_points_
Definition: unit.hpp:1885
int movement_
Definition: unit.hpp:1908
void generate_name()
Generates a random race-appropriate name if one has not already been provided.
Definition: unit.cpp:731
std::vector< t_string > trait_names_
Definition: unit.hpp:1946
int unit_value_
Definition: unit.hpp:1949
int attacks_left_
Definition: unit.hpp:1919
bool generate_name_
Definition: unit.hpp:1977
movetype movement_type_
Definition: unit.hpp:1913
config variables_
Definition: unit.hpp:1929
bool unrenamable_
Definition: unit.hpp:1900
int experience_
Definition: unit.hpp:1887
int vision_
Definition: unit.hpp:1910
void remove_ability_by_attribute(const config &filter)
Removes a unit's abilities with a specific ID or other attribute.
Definition: unit.cpp:1531
std::string undead_variation_
Definition: unit.hpp:1882
t_string type_name_
The displayed name of this unit type.
Definition: unit.hpp:1873
std::optional< std::string > ellipse_
Definition: unit.hpp:1974
map_location::DIRECTION facing_
Definition: unit.hpp:1943
unit_movement_resetter(const unit_movement_resetter &)=delete
bool random_traits_
Definition: unit.hpp:1976
void write(config &cfg, bool write_all=true) const
Serializes the current unit metadata values.
Definition: unit.cpp:1554
std::bitset< UA_COUNT > changed_attributes_
Definition: unit.hpp:1986
std::string small_profile_
Definition: unit.hpp:1982
void write_upkeep(config::attribute_value &upkeep) const
Definition: unit.cpp:2827
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:182
std::string id_
Definition: unit.hpp:1878
std::vector< t_string > special_notes_
Definition: unit.hpp:1970
bool canrecruit_
Definition: unit.hpp:1893
std::string image_mods_
Definition: unit.hpp:1898
double hp_bar_scaling_
Definition: unit.hpp:1962
std::string flag_rgb_
Definition: unit.hpp:1897
static std::map< std::string, state_t > known_boolean_state_names_
Definition: unit.hpp:1927
@ UA_IS_HEALTHY
Definition: unit.hpp:167
@ UA_SMALL_PROFILE
Definition: unit.hpp:180
@ UA_MAX_MP
Definition: unit.hpp:164
@ UA_ATTACKS
Definition: unit.hpp:177
@ UA_ZOC
Definition: unit.hpp:171
@ UA_MOVEMENT_TYPE
Definition: unit.hpp:170
@ UA_PROFILE
Definition: unit.hpp:179
@ UA_LEVEL
Definition: unit.hpp:169
@ UA_MAX_XP
Definition: unit.hpp:166
@ UA_IS_FEARLESS
Definition: unit.hpp:168
@ UA_ADVANCE_TO
Definition: unit.hpp:172
@ UA_MAX_AP
Definition: unit.hpp:165
@ UA_ADVANCEMENTS
Definition: unit.hpp:173
@ UA_MAX_HP
Definition: unit.hpp:163
@ UA_ABILITIES
Definition: unit.hpp:181
@ UA_NOTES
Definition: unit.hpp:178
@ UA_ALIGNMENT
Definition: unit.hpp:174
config events_
Definition: unit.hpp:1930
bool hidden_
Definition: unit.hpp:1961
bool is_healthy_
Definition: unit.hpp:1952
bool is_fearless_
Definition: unit.hpp:1952
config abilities_
Definition: unit.hpp:1965
unit_ability_list get_abilities_weapons(const std::string &tag_name, const map_location &loc, const_attack_ptr weapon=nullptr, const_attack_ptr opp_weapon=nullptr) const
Definition: abilities.cpp:260
const unit_type * type_
Never nullptr.
Definition: unit.hpp:1870
std::bitset< num_bool_states > known_boolean_states_
Definition: unit.hpp:1926
int side_
Definition: unit.hpp:1902
const unit_race * race_
Never nullptr, but may point to the null race.
Definition: unit.hpp:1876
bool appearance_changed_
Definition: unit.hpp:1985
double xp_bar_scaling_
Definition: unit.hpp:1962
unit_alignments::type alignment_
Definition: unit.hpp:1895
bool invisible(const map_location &loc, bool see_all=true) const
Definition: unit.cpp:2596
bool is_visible_to_team(const team &team, bool const see_all=true) const
Definition: unit.cpp:2639
n_unit::unit_id underlying_id_
Definition: unit.hpp:1880
std::string variation_
Definition: unit.hpp:1883
unit & mark_clone(bool is_temporary)
Mark this unit as clone so it can be inserted to unit_map.
Definition: unit.cpp:2697
config filter_recall_
Definition: unit.hpp:1931
int max_experience_
Definition: unit.hpp:1888
unit_ability_list get_abilities(const std::string &tag_name, const map_location &loc) const
Gets the unit's active abilities of a particular type if it were on a specified location.
Definition: abilities.cpp:220
unit_race::GENDER gender_
Definition: unit.hpp:1904
t_string description_
Definition: unit.hpp:1969
int level_
Definition: unit.hpp:1890
std::string role_
Definition: unit.hpp:1937
std::map< map_location, bool > invisibility_cache_
Hold the visibility status cache for a unit, when not uncovered.
Definition: unit.hpp:1995
bool end_turn_
Definition: unit.hpp:1916
std::vector< std::string > advances_to_
Definition: unit.hpp:1867
std::unique_ptr< unit_animation_component > anim_comp_
Definition: unit.hpp:1959
int recall_cost_
Definition: unit.hpp:1892
static std::string type()
Definition: unit.hpp:1135
attack_list attacks_
Definition: unit.hpp:1938
void remove_ability_by_id(const std::string &ability)
Removes a unit's abilities with a specific ID.
Definition: unit.cpp:1411
map_location loc_
Definition: unit.hpp:1865
std::vector< std::string > overlays_
Definition: unit.hpp:1935
config modifications_
Definition: unit.hpp:1964
bool has_ability_by_id(const std::string &ability) const
Check if the unit has an ability of a specific ID.
Definition: unit.cpp:1400
bool hold_position_
Definition: unit.hpp:1915
const config & abilities() const
Definition: unit.hpp:1724
void parse_upkeep(const config::attribute_value &upkeep)
Definition: unit.cpp:2813
std::vector< std::string > recruit_list_
Definition: unit.hpp:1894
std::vector< config > advancements_
Definition: unit.hpp:1967
utils::string_map modification_descriptions_
Definition: unit.hpp:1954
unit_checksum_version
Optional parameter for get_checksum to use the algorithm of an older version of Wesnoth,...
Definition: unit.hpp:2034
upkeep_t upkeep_
Definition: unit.hpp:1979
std::set< std::string > states_
Definition: unit.hpp:1922
std::string profile_
Definition: unit.hpp:1981
int jamming_
Definition: unit.hpp:1911
std::optional< std::string > halo_
Definition: unit.hpp:1973
map_location goto_
Definition: unit.hpp:1950
t_string name_
Definition: unit.hpp:1879
int max_attacks_
Definition: unit.hpp:1920
bool ability_matches_filter(const config &cfg, const std::string &tag_name, const config &filter) const
Verify what abilities attributes match with filter.
Definition: unit.cpp:1507
int max_hit_points_
Definition: unit.hpp:1886
std::unique_ptr< unit_formula_manager > formula_man_
Definition: unit.hpp:1906
int max_movement_
Definition: unit.hpp:1909
bool resting_
Definition: unit.hpp:1917
std::vector< t_string > trait_descriptions_
Definition: unit.hpp:1947
bool emit_zoc_
Definition: unit.hpp:1933
std::optional< std::string > usage_
Definition: unit.hpp:1972
@ version_1_16_or_older
Included some of the flavortext from weapon specials.
void set_big_profile(const std::string &value)
Definition: unit.cpp:1940
int max_hitpoints() const
The max number of hitpoints this unit can have.
Definition: unit.hpp:506
void heal(int amount)
Heal the unit.
Definition: unit.cpp:1295
void set_state(const std::string &state, bool value)
Set whether the unit is affected by a status effect.
Definition: unit.cpp:1377
void new_turn()
Refresh unit for the beginning of a turn.
Definition: unit.cpp:1256
const std::vector< std::string > & recruits() const
The type IDs of the other units this unit may recruit, if possible.
Definition: unit.hpp:625
void set_max_experience(int value)
Definition: unit.hpp:535
void set_max_hitpoints(int value)
Definition: unit.hpp:511
int recall_cost() const
How much gold it costs to recall this unit, or -1 if the side's default recall cost is used.
Definition: unit.hpp:641
std::string big_profile() const
An optional profile image displays when this unit is 'speaking' via [message].
Definition: unit.cpp:1029
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
void set_level(int level)
Sets the current level of this unit.
Definition: unit.hpp:566
void set_hidden(bool state) const
Sets whether the unit is hidden on the map.
Definition: unit.cpp:2793
const std::string & variation() const
The ID of the variation of this unit's type.
Definition: unit.hpp:573
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:500
bool get_state(const std::string &state) const
Check if the unit is affected by a status effect.
Definition: unit.cpp:1328
std::string small_profile() const
An optional profile image to display in Help.
Definition: unit.cpp:1038
void heal_fully()
Fully heal the unit, restoring it to max hitpoints.
Definition: unit.hpp:832
void set_undead_variation(const std::string &value)
The ID of the undead variation (ie, dwarf, swimmer) of this unit.
Definition: unit.hpp:579
const std::string & type_id() const
The id of this unit's type.
Definition: unit.cpp:1935
void set_alignment(unit_alignments::type alignment)
Sets the alignment of this unit.
Definition: unit.hpp:482
const std::set< std::string > get_states() const
Get the status effects currently affecting the unit.
Definition: unit.cpp:1311
void new_scenario()
Refresh unit for the beginning of a new scenario.
Definition: unit.cpp:1280
void end_turn()
Refresh unit for the end of a turn.
Definition: unit.cpp:1266
const unit_type & type() const
This unit's type, accounting for gender and variation.
Definition: unit.hpp:356
bool can_recruit() const
Whether this unit can recruit other units - ie, are they a leader unit.
Definition: unit.hpp:613
const std::string & id() const
Gets this unit's id.
Definition: unit.hpp:381
void set_underlying_id(n_unit::id_manager &id_manager)
Sets the internal ID.
Definition: unit.cpp:2680
int side() const
The side this unit belongs to.
Definition: unit.hpp:344
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:542
state_t
Built-in status effects known to the engine.
Definition: unit.hpp:860
void set_recruits(const std::vector< std::string > &recruits)
Sets the recruit list.
Definition: unit.cpp:1165
std::vector< t_string > unit_special_notes() const
The unit's special notes.
Definition: unit.cpp:2840
config & variables()
Gets any user-defined variables this unit 'owns'.
Definition: unit.hpp:704
void set_usage(const std::string &usage)
Sets this unit's usage.
Definition: unit.hpp:693
void set_small_profile(const std::string &value)
Definition: unit.hpp:597
unit_race::GENDER gender() const
The gender of this unit.
Definition: unit.hpp:466
const t_string & name() const
Gets this unit's translatable display name.
Definition: unit.hpp:404
@ STATE_SLOWED
Definition: unit.hpp:861
@ STATE_UNKNOWN
To set the size of known_boolean_states_.
Definition: unit.hpp:870
@ STATE_NOT_MOVED
The unit is uncovered - it was hiding but has been spotted.
Definition: unit.hpp:865
@ STATE_GUARDIAN
The unit cannot be healed.
Definition: unit.hpp:867
@ STATE_INVULNERABLE
The unit is a guardian - it won't move unless a target is sighted.
Definition: unit.hpp:868
@ STATE_PETRIFIED
The unit is poisoned - it loses health each turn.
Definition: unit.hpp:863
@ STATE_POISONED
The unit is slowed - it moves slower and does less damage.
Definition: unit.hpp:862
@ STATE_UNCOVERED
The unit is petrified - it cannot move or be attacked.
Definition: unit.hpp:864
std::vector< std::string > advances_to_t
Definition: unit.hpp:239
std::vector< config > get_modification_advances() const
Gets any non-typed advanced options set by modifications.
Definition: unit.cpp:1864
std::vector< std::pair< std::string, std::string > > amla_icons() const
Gets the image and description data for modification advancements.
Definition: unit.cpp:1847
const advances_to_t & advances_to() const
Gets the possible types this unit can advance to on level-up.
Definition: unit.hpp:245
bool can_advance() const
Checks whether this unit has any options to advance to.
Definition: unit.hpp:273
void set_advancements(std::vector< config > advancements)
Sets the raw modification advancement option data.
Definition: unit.cpp:1929
void set_advances_to(const std::vector< std::string > &advances_to)
Sets this unit's advancement options.
Definition: unit.cpp:1186
const std::vector< config > & modification_advancements() const
The raw, unparsed data for modification advancements.
Definition: unit.hpp:324
std::map< std::string, std::string > advancement_icons() const
Gets and image path and and associated description for each advancement option.
Definition: unit.cpp:1807
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
void advance_to(const unit_type &t, bool use_traits=false)
Advances this unit to another type.
Definition: unit.cpp:893
void remove_attacks_ai()
Set the unit to have no attacks left for this turn.
Definition: unit.cpp:2775
bool resistance_filter_matches(const config &cfg, bool attacker, const std::string &damage_name, int res) const
Definition: unit.cpp:1758
void set_max_attacks(int value)
Definition: unit.hpp:984
int defense_modifier(const t_translation::terrain_code &terrain) const
The unit's defense on a given terrain.
Definition: unit.cpp:1743
bool remove_attack(attack_ptr atk)
Remove an attack from the unit.
Definition: unit.cpp:2764
attack_itors attacks()
Gets an iterator over this unit's attacks.
Definition: unit.hpp:928
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's resistance against a given damage type.
Definition: unit.cpp:1786
void set_attacks(int left)
Sets the number of attacks this unit has left this turn.
Definition: unit.hpp:1016
color_t xp_color() const
Color for this unit's XP.
Definition: unit.cpp:1153
color_t hp_color() const
Color for this unit's current hitpoints.
Definition: unit.cpp:1099
std::string TC_image_mods() const
Constructs a recolor (RC) IPF string for this unit's team color.
Definition: unit.cpp:2749
static color_t hp_color_max()
Definition: unit.cpp:1109
const std::string & flag_rgb() const
Get the source color palette to use when recoloring the unit's image.
Definition: unit.cpp:1056
std::string image_mods() const
Gets an IPF string containing all IPF image mods.
Definition: unit.cpp:2754
std::string default_anim_image() const
The default image to use for animation frames with no defined image.
Definition: unit.cpp:2578
const std::vector< std::string > & overlays() const
Get the unit's overlay images.
Definition: unit.hpp:1600
std::string absolute_image() const
The name of the file to game_display (used in menus).
Definition: unit.cpp:2573
void set_image_ellipse(const std::string &ellipse)
Set the unit's ellipse image.
Definition: unit.hpp:1572
void set_image_halo(const std::string &halo)
Set the unit's halo image.
Definition: unit.cpp:2806
void apply_builtin_effect(std::string type, const config &effect)
Apply a builtin effect to the unit.
Definition: unit.cpp:2038
void add_modification(const std::string &type, const config &modification, bool no_add=false)
Add a new modification to the unit.
Definition: unit.cpp:2420
static const std::set< std::string > builtin_effects
Definition: unit.hpp:1518
std::string describe_builtin_effect(std::string type, const config &effect)
Construct a string describing a built-in effect.
Definition: unit.cpp:1973
void apply_modifications()
Re-apply all saved modifications.
Definition: unit.cpp:2583
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:1947
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1358
void set_facing(map_location::DIRECTION dir) const
The this unit's facing.
Definition: unit.cpp:1719
const movetype & movement_type() const
Get the unit's movement type.
Definition: unit.hpp:1431
void set_movement(int moves, bool unit_action=false)
Set this unit's remaining movement to moves.
Definition: unit.cpp:1193
void set_total_movement(int value)
Definition: unit.hpp:1272
void set_emit_zoc(bool val)
Sets the raw zone-of-control flag.
Definition: unit.hpp:1351
int movement_left() const
Gets how far a unit can move, considering the incapacitated flag.
Definition: unit.hpp:1283
int total_movement() const
The maximum moves this unit has.
Definition: unit.hpp:1267
void remove_movement_ai()
Sets the unit to have no moves left for this turn.
Definition: unit.cpp:2784
void set_interrupted_move(const map_location &interrupted_move)
Set the target location of the unit's interrupted move.
Definition: unit.hpp:1425
int upkeep() const
Gets the amount of gold this unit costs a side per turn.
Definition: unit.cpp:1728
void add_trait_description(const config &trait, const t_string &description)
Register a trait's name and its description for the UI's use.
Definition: unit.cpp:2560
std::vector< std::string > get_traits_list() const
Gets a list of the traits this unit currently has.
Definition: unit.cpp:873
void generate_traits(bool must_have_only=false)
Applies mandatory traits (e.g.
Definition: unit.cpp:740
bool loyal() const
Gets whether this unit is loyal - ie, it costs no upkeep.
Definition: unit.cpp:1738
std::string tooltip
Shown when hovering over an entry in the filter's drop-down list.
Definition: manager.cpp:219
New lexcical_cast header.
Standard logging facilities (interface).
#define log_scope(description)
Definition: log.hpp:241
A small explanation about what's going on here: Each action has access to two game_info objects First...
Definition: actions.cpp:61
void set(CURSOR_TYPE type)
Use the default parameter to reset cursors.
Definition: cursor.cpp:176
Handling of system events.
Definition: manager.hpp:43
int kill_experience
Definition: game_config.cpp:40
std::string unit_rgb
static void add_color_info(const game_config_view &v, bool build_defaults)
void remove()
Removes a tip.
Definition: tooltip.cpp:111
Definition: display.hpp:45
std::pair< std::string, unsigned > item
Definition: help_impl.hpp:414
Functions to load and save images from/to disk.
Main entry points of multiplayer mode.
Definition: lobby_data.cpp:52
std::set< std::string > & encountered_units()
Definition: game.cpp:916
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:61
game_board * gameboard
Definition: resources.cpp:21
game_data * gamedata
Definition: resources.cpp:23
game_events::manager * game_events
Definition: resources.cpp:25
game_lua_kernel * lua_kernel
Definition: resources.cpp:26
filter_context * filter_con
Definition: resources.cpp:24
bool filter_base_matches(const config &cfg, int def)
Definition: abilities.cpp:1742
Utility functions for implementing [filter], [filter_ability], [filter_weapon], etc.
bool double_matches_if_present(const config &filter, const config &cfg, const std::string &attribute)
bool int_matches_if_present(const config &filter, const config &cfg, const std::string &attribute)
bool string_matches_if_present(const config &filter, const config &cfg, const std::string &attribute, const std::string &def)
bool int_matches_if_present_or_negative(const config &filter, const config &cfg, const std::string &attribute, const std::string &opposite)
Supports filters using "add" and "sub" attributes, for example a filter add=1 matching a cfg containi...
bool bool_matches_if_present(const config &filter, const config &cfg, const std::string &attribute, bool def)
Checks whether the filter matches the value of cfg[attribute].
std::string get_unknown_exception_type()
Utility function for finding the type of thing caught with catch(...).
Definition: general.cpp:23
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...
void erase_if(Container &container, const Predicate &predicate)
Convenience wrapper for using std::remove_if on a container.
Definition: general.hpp:104
int apply_modifier(const int number, const std::string &amount, const int minimum)
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
std::string format_conjunct_list(const t_string &empty, const std::vector< t_string > &elems)
Format a conjunctive list.
std::map< std::string, t_string > string_map
std::vector< std::string > split(const config_attribute_value &val)
std::string print_modifier(const std::string &mod)
Add a "+" or replace the "-" par Unicode minus.
std::string::const_iterator iterator
Definition: tokenizer.hpp:25
std::shared_ptr< const attack_type > const_attack_ptr
Definition: ptr.hpp:34
std::shared_ptr< attack_type > attack_ptr
Definition: ptr.hpp:33
const std::string & gender_string(unit_race::GENDER gender)
Definition: race.cpp:142
unit_race::GENDER string_gender(const std::string &str, unit_race::GENDER def)
Definition: race.cpp:152
const config::attribute_value & gender_value(const config &cfg, unit_race::GENDER gender, const std::string &male_key, const std::string &female_key, const std::string &default_key)
Chooses a value from the given config based on gender.
Definition: race.cpp:161
The basic class for representing 8-bit RGB or RGBA colour values.
Definition: color.hpp:59
Encapsulates the map of the game.
Definition: location.hpp:38
static DIRECTION parse_direction(const std::string &str)
Definition: location.cpp:66
DIRECTION
Valid directions which can be moved in our hexagonal world.
Definition: location.hpp:40
void set_wml_y(int v)
Definition: location.hpp:157
int wml_y() const
Definition: location.hpp:154
void set_wml_x(int v)
Definition: location.hpp:156
int wml_x() const
Definition: location.hpp:153
static std::string write_direction(DIRECTION dir)
Definition: location.cpp:141
bool is_fake() const
Definition: id.hpp:29
std::size_t value
Definition: id.hpp:27
static std::string get_string(enum_type key)
Converts a enum to its string equivalent.
Definition: enum_base.hpp:46
static constexpr std::optional< enum_type > get_enum(const std::string_view value)
Converts a string into its enum equivalent.
Definition: enum_base.hpp:57
A terrain string which is converted to a terrain is a string with 1 or 2 layers the layers are separa...
Definition: translation.hpp:49
Visitor helper struct to fetch the upkeep type flag if applicable, or the the value otherwise.
Definition: unit.hpp:1175
Data typedef for unit_ability_list.
Definition: unit.hpp:40
void validate_side(int side)
Definition: team.cpp:757
mock_char c
static map_location::DIRECTION s
unit_type_data unit_types
Definition: types.cpp:1465
std::vector< t_string > combine_special_notes(const std::vector< t_string > direct, const config &abilities, const_attack_itors attacks, const movetype &mt)
Common logic for unit_type::special_notes() and unit::special_notes().
Definition: types.cpp:507
void adjust_profile(std::string &profile)
Definition: types.cpp:1467
#define WRN_UT
Definition: unit.cpp:72
static lg::log_domain log_unit("unit")
static bool type_value_if_present(const config &filter, const config &cfg)
Definition: unit.cpp:1424
static bool matches_ability_filter(const config &cfg, const std::string &tag_name, const config &filter)
Definition: unit.cpp:1446
static const unit_type & get_unit_type(const std::string &type_id)
Converts a string ID to a unit_type.
Definition: unit.cpp:191
static unit_race::GENDER generate_gender(const unit_type &type, bool random_gender)
Definition: unit.cpp:203
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
#define LOG_UT
Definition: unit.cpp:71
#define DBG_UT
Definition: unit.cpp:70
std::string get_checksum(const unit &u, backwards_compatibility::unit_checksum_version version)
Gets a checksum for a unit.
Definition: unit.cpp:2846
static color_t hp_color_impl(int hitpoints, int max_hitpoints)
Definition: unit.cpp:1061
#define ERR_UT
Definition: unit.cpp:73
#define e
#define a