The Battle for Wesnoth  1.15.6+dev
game_lua_kernel.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2009 - 2018 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 /**
16  * @file
17  * Provides a Lua interpreter, to be embedded in WML.
18  *
19  * @note Naming conventions:
20  * - intf_ functions are exported in the wesnoth domain,
21  * - impl_ functions are hidden inside metatables,
22  * - cfun_ functions are closures,
23  * - luaW_ functions are helpers in Lua style.
24  */
25 
27 
28 #include "actions/attack.hpp" // for battle_context_unit_stats, etc
29 #include "actions/advancement.hpp" // for advance_unit_at, etc
30 #include "actions/move.hpp" // for clear_shroud
31 #include "actions/vision.hpp" // for clear_shroud
32 #include "ai/composite/ai.hpp" // for ai_composite
33 #include "ai/composite/component.hpp" // for component, etc
34 #include "ai/composite/contexts.hpp" // for ai_context
35 #include "ai/lua/engine_lua.hpp" // for engine_lua
36 #include "ai/composite/rca.hpp" // for candidate_action
37 #include "ai/composite/stage.hpp" // for stage
38 #include "ai/configuration.hpp" // for configuration
39 #include "ai/lua/core.hpp" // for lua_ai_context, etc
40 #include "ai/manager.hpp" // for manager, holder
41 #include "attack_prediction.hpp" // for combatant
42 #include "chat_events.hpp" // for chat_handler, etc
43 #include "config.hpp" // for config, etc
44 #include "display_chat_manager.hpp" // for clear_chat_messages
45 #include "floating_label.hpp"
46 #include "formatter.hpp"
47 #include "game_board.hpp" // for game_board
48 #include "game_classification.hpp" // for game_classification, etc
49 #include "game_config.hpp" // for debug, base_income, etc
50 #include "game_config_manager.hpp" // for game_config_manager
51 #include "game_data.hpp" // for game_data, etc
52 #include "game_display.hpp" // for game_display
53 #include "game_errors.hpp" // for game_error
54 #include "game_events/conditional_wml.hpp" // for conditional_passed
56 #include "game_events/pump.hpp" // for queued_event
57 #include "preferences/game.hpp" // for encountered_units
58 #include "help/help.hpp"
59 #include "log.hpp" // for LOG_STREAM, logger, etc
60 #include "utils/make_enum.hpp" // for operator<<
61 #include "map/map.hpp" // for gamemap
62 #include "map/label.hpp"
63 #include "map/location.hpp" // for map_location
64 #include "mouse_events.hpp" // for mouse_handler
65 #include "mp_game_settings.hpp" // for mp_game_settings
66 #include "pathfind/pathfind.hpp" // for full_cost_map, plain_route, etc
67 #include "pathfind/teleport.hpp" // for get_teleport_locations, etc
68 #include "play_controller.hpp" // for play_controller
69 #include "recall_list_manager.hpp" // for recall_list_manager
70 #include "replay.hpp" // for get_user_choice, etc
71 #include "reports.hpp" // for register_generator, etc
72 #include "resources.hpp" // for whiteboard
73 #include "scripting/lua_audio.hpp"
74 #include "scripting/lua_unit.hpp"
76 #include "scripting/lua_common.hpp"
78 #include "scripting/lua_gui2.hpp" // for show_gamestate_inspector
80 #include "scripting/lua_race.hpp"
81 #include "scripting/lua_team.hpp"
83 #include "scripting/push_check.hpp"
84 #include "synced_commands.hpp"
85 #include "color.hpp" // for surface
86 #include "sdl/surface.hpp" // for surface
87 #include "side_filter.hpp" // for side_filter
88 #include "sound.hpp" // for commit_music_changes, etc
89 #include "soundsource.hpp"
90 #include "synced_context.hpp" // for synced_context, etc
91 #include "synced_user_choice.hpp"
92 #include "team.hpp" // for team, village_owner
93 #include "terrain/terrain.hpp" // for terrain_type
94 #include "terrain/filter.hpp" // for terrain_filter
95 #include "terrain/translation.hpp" // for read_terrain_code, etc
96 #include "terrain/type_data.hpp"
97 #include "time_of_day.hpp" // for time_of_day
98 #include "tod_manager.hpp" // for tod_manager
99 #include "tstring.hpp" // for t_string, operator+
100 #include "units/unit.hpp" // for unit
101 #include "units/animation_component.hpp" // for unit_animation_component
102 #include "units/udisplay.hpp"
103 #include "units/filter.hpp"
104 #include "units/map.hpp" // for unit_map, etc
105 #include "units/ptr.hpp" // for unit_const_ptr, unit_ptr
106 #include "units/types.hpp" // for unit_type_data, unit_types, etc
107 #include "variable.hpp" // for vconfig, etc
108 #include "variable_info.hpp"
109 #include "whiteboard/manager.hpp" // for whiteboard
110 #include "wml_exception.hpp"
111 #include "deprecation.hpp"
112 
113 #include "utils/functional.hpp" // for bind_t, bind
114 #include <boost/range/algorithm/copy.hpp> // boost::copy
115 #include <boost/range/adaptors.hpp> // boost::adaptors::filtered
116 #include <array>
117 #include <cassert> // for assert
118 #include <cstring> // for strcmp
119 #include <iterator> // for distance, advance
120 #include <map> // for map, map<>::value_type, etc
121 #include <new> // for operator new
122 #include <set> // for set
123 #include <sstream> // for operator<<, basic_ostream, etc
124 #include <utility> // for pair
125 #include <algorithm>
126 #include <vector> // for vector, etc
127 #include <SDL2/SDL_timer.h> // for SDL_GetTicks
128 #include "lua/lauxlib.h" // for luaL_checkinteger, etc
129 #include "lua/lua.h" // for lua_setfield, etc
130 
131 class CVideo;
132 
133 #ifdef DEBUG_LUA
134 #include "scripting/debug_lua.hpp"
135 #endif
136 
137 static lg::log_domain log_scripting_lua("scripting/lua");
138 #define LOG_LUA LOG_STREAM(info, log_scripting_lua)
139 #define WRN_LUA LOG_STREAM(warn, log_scripting_lua)
140 #define ERR_LUA LOG_STREAM(err, log_scripting_lua)
141 
142 std::vector<config> game_lua_kernel::preload_scripts;
144 
145 // Template which allows to push member functions to the lua kernel base into lua as C functions, using a shim
147 
148 template <member_callback method>
150  return ((lua_kernel_base::get_lua_kernel<game_lua_kernel>(L)).*method)(L);
151 }
152 
153 // Pass a const bool also...
154 typedef int (game_lua_kernel::*member_callback2)(lua_State *, bool);
155 
156 template <member_callback2 method, bool b>
158  return ((lua_kernel_base::get_lua_kernel<game_lua_kernel>(L)).*method)(L, b);
159 }
160 
162 {
163  map_locker(game_lua_kernel* kernel) : kernel_(kernel)
164  {
165  ++kernel_->map_locked_;
166  }
168  {
169  --kernel_->map_locked_;
170  }
172 };
173 
174 
176 {
177  game_lua_kernel::preload_scripts.clear();
178  for (const config& cfg : game_config.child_range("lua")) {
179  game_lua_kernel::preload_scripts.push_back(cfg);
180  }
181  game_lua_kernel::preload_config = game_config.child("game_config");
182 }
183 
184 void game_lua_kernel::log_error(char const * msg, char const * context)
185 {
186  lua_kernel_base::log_error(msg, context);
187  lua_chat(context, msg);
188 }
189 
191 {
192  if (game_display_) {
193  game_display_->get_chat_manager().add_chat_message(std::time(nullptr), caption, 0, msg,
195  }
196 }
197 
198 /**
199  * Gets a vector of sides from side= attribute in a given config node.
200  * Promotes consistent behavior.
201  */
202 std::vector<int> game_lua_kernel::get_sides_vector(const vconfig& cfg)
203 {
204  const config::attribute_value sides = cfg["side"];
205  const vconfig &ssf = cfg.child("filter_side");
206 
207  if (!ssf.null()) {
208  if(!sides.empty()) { WRN_LUA << "ignoring duplicate side filter information (inline side=)" << std::endl; }
209  side_filter filter(ssf, &game_state_);
210  return filter.get_teams();
211  }
212 
213  side_filter filter(sides.str(), &game_state_);
214  return filter.get_teams();
215 }
216 
217 
218 
220 {
221  lua_pushnumber(L, lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).map().special_locations().size());
222  return 1;
223 }
224 
226 {
227  const t_translation::starting_positions::left_map& left = lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).map().special_locations().left;
228 
229  t_translation::starting_positions::left_const_iterator it;
230  if (lua_isnoneornil(L, 2)) {
231  it = left.begin();
232  }
233  else {
234  it = left.find(luaL_checkstring(L, 2));
235  if (it == left.end()) {
236  return 0;
237  }
238  ++it;
239  }
240  if (it == left.end()) {
241  return 0;
242  }
243  lua_pushstring(L, it->first.c_str());
244  luaW_pushlocation(L, it->second);
245  return 2;
246 }
247 
249 {
251  lua_pushvalue(L, -2);
252  lua_pushnil(L);
253  return 3;
254 }
255 
257 {
258  const t_translation::starting_positions::left_map& left = lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).map().special_locations().left;
259  auto it = left.find(luaL_checkstring(L, 2));
260  if (it == left.end()) {
261  return 0;
262  }
263  else {
264  luaW_pushlocation(L, it->second);
265  return 1;
266  }
267 }
268 
270 {
271  lua_pushstring(L, "special locations cannot be modified using wesnoth.special_locations");
272  return lua_error(L);
273 }
274 
276 {
277  lua_newtable(L); // The functor table
278  lua_newtable(L); // The functor metatable
279  lua_pushstring(L, "__len");
281  lua_rawset(L, -3);
282  lua_pushstring(L, "__index");
284  lua_rawset(L, -3);
285  lua_pushstring(L, "__newindex");
287  lua_rawset(L, -3);
288  lua_pushstring(L, "__pairs");
290  lua_rawset(L, -3);
291  lua_setmetatable(L, -2); // Apply the metatable to the functor table
292 }
293 
294 namespace {
295  /**
296  * Temporary entry to a queued_event stack
297  */
298  struct queued_event_context
299  {
300  typedef game_events::queued_event qe;
301  std::stack<qe const *> & stack_;
302 
303  queued_event_context(qe const *new_qe, std::stack<qe const*> & stack)
304  : stack_(stack)
305  {
306  stack_.push(new_qe);
307  }
308 
309  ~queued_event_context()
310  {
311  stack_.pop();
312  }
313  };
314 }//unnamed namespace for queued_event_context
315 
316 /**
317  * Gets currently viewing side.
318  * - Ret 1: integer specifying the currently viewing side
319  * - Ret 2: Bool whether the vision is not limited to that team, this can for example be true during replays.
320  */
322 {
323  if(const display* disp = display::get_singleton()) {
324  lua_pushinteger(L, disp->viewing_side());
325  lua_pushboolean(L, disp->show_everything());
326  return 2;
327  }
328  else {
329  return 0;
330  }
331 }
332 
333 static const char animatorKey[] = "unit animator";
334 
336  unit_animator& anim = *static_cast<unit_animator*>(luaL_checkudata(L, 1, animatorKey));
337  anim.~unit_animator();
338  return 0;
339 }
340 
342 {
343  unit_animator& anim = *static_cast<unit_animator*>(luaL_checkudata(L, 1, animatorKey));
344  unit_ptr up = luaW_checkunit_ptr(L, 2, false);
345  unit& u = *up;
346  std::string which = luaL_checkstring(L, 3);
347 
348  using hit_type = unit_animation::hit_type;
349  std::string hits_str = luaL_checkstring(L, 4);
350  hit_type hits = hit_type::string_to_enum(hits_str, hit_type::INVALID);
351 
352  map_location dest;
353  int v1 = 0, v2 = 0;
354  bool bars = false;
355  t_string text;
356  color_t color{255, 255, 255};
357  const_attack_ptr primary, secondary;
358 
359  if(lua_istable(L, 5)) {
360  lua_getfield(L, 5, "target");
361  if(luaW_tolocation(L, -1, dest)) {
362  if(dest == u.get_location()) {
363  return luaL_argerror(L, 5, "target location must be different from animated unit's location");
364  } else if(!tiles_adjacent(dest, u.get_location())) {
365  return luaL_argerror(L, 5, "target location must be adjacent to the animated unit");
366  }
367  } else {
368  // luaW_tolocation may set the location to (0,0) if it fails
369  dest = map_location();
370  if(!lua_isnoneornil(L, -1)) {
371  return luaW_type_error(L, 5, "target", "location table");
372  }
373  }
374  lua_pop(L, 1);
375 
376  lua_getfield(L, 5, "value");
377  if(lua_isnumber(L, -1)) {
378  v1 = lua_tonumber(L, -1);
379  } else if(lua_istable(L, -1)) {
380  lua_rawgeti(L, -1, 1);
381  v1 = lua_tonumber(L, -1);
382  lua_pop(L, 1);
383  lua_rawgeti(L, -1, 2);
384  v2 = lua_tonumber(L, -1);
385  lua_pop(L, 1);
386  } else if(!lua_isnoneornil(L, -1)) {
387  return luaW_type_error(L, 5, "value", "number or array of two numbers");
388  }
389  lua_pop(L, 1);
390 
391  lua_getfield(L, 5, "with_bars");
392  if(lua_isboolean(L, -1)) {
393  bars = luaW_toboolean(L, -1);
394  } else if(!lua_isnoneornil(L, -1)) {
395  return luaW_type_error(L, 5, "with_bars", lua_typename(L, LUA_TBOOLEAN));
396  }
397  lua_pop(L, 1);
398 
399  lua_getfield(L, 5, "text");
400  if(lua_isstring(L, -1)) {
401  text = lua_tostring(L, -1);
402  } else if(luaW_totstring(L, -1, text)) {
403  // Do nothing; luaW_totstring already assigned the value
404  } else if(!lua_isnoneornil(L, -1)) {
405  return luaW_type_error(L, 5, "text", lua_typename(L, LUA_TSTRING));
406  }
407  lua_pop(L, 1);
408 
409  lua_getfield(L, 5, "color");
410  if(lua_istable(L, -1) && lua_rawlen(L, -1) == 3) {
411  int idx = lua_absindex(L, -1);
412  lua_rawgeti(L, idx, 1); // red @ -3
413  lua_rawgeti(L, idx, 2); // green @ -2
414  lua_rawgeti(L, idx, 3); // blue @ -1
415  color = color_t(lua_tonumber(L, -3), lua_tonumber(L, -2), lua_tonumber(L, -1));
416  lua_pop(L, 3);
417  } else if(!lua_isnoneornil(L, -1)) {
418  return luaW_type_error(L, 5, "color", "array of three numbers");
419  }
420  lua_pop(L, 1);
421 
422  lua_getfield(L, 5, "primary");
423  primary = luaW_toweapon(L, -1);
424  if(!primary && !lua_isnoneornil(L, -1)) {
425  return luaW_type_error(L, 5, "primary", "weapon");
426  }
427  lua_pop(L, 1);
428 
429  lua_getfield(L, 5, "secondary");
430  secondary = luaW_toweapon(L, -1);
431  if(!secondary && !lua_isnoneornil(L, -1)) {
432  return luaW_type_error(L, 5, "secondary", "weapon");
433  }
434  lua_pop(L, 1);
435  } else if(!lua_isnoneornil(L, 5)) {
436  return luaW_type_error(L, 5, "table of options");
437  }
438 
439  anim.add_animation(up, which, u.get_location(), dest, v1, bars, text, color, hits, primary, secondary, v2);
440  return 0;
441 }
442 
444 {
446  if(v.update_locked() || v.faked()) {
447  return 0;
448  }
449  events::command_disabler command_disabler;
450  unit_animator& anim = *static_cast<unit_animator*>(luaL_checkudata(L, 1, animatorKey));
451  play_controller_.play_slice(false);
452  anim.start_animations();
453  anim.wait_for_end();
454  anim.set_all_standing();
455  anim.clear();
456  return 0;
457 }
458 
460 {
461  unit_animator& anim = *static_cast<unit_animator*>(luaL_checkudata(L, 1, animatorKey));
462  anim.clear();
463  return 0;
464 }
465 
467 {
468  const char* m = lua_tostring(L, 2);
469  return luaW_getmetafield(L, 1, m);
470 }
471 
473 {
474  new(L) unit_animator;
476  luaL_Reg metafuncs[] {
477  {"__gc", impl_animator_collect},
478  {"__index", impl_animator_get},
479  {"add", impl_add_animation},
480  {"run", &dispatch<&game_lua_kernel::impl_run_animation>},
481  {"clear", impl_clear_animation},
482  {nullptr, nullptr},
483  };
484  luaL_setfuncs(L, metafuncs, 0);
485  lua_pushstring(L, "__metatable");
486  lua_setfield(L, -2, animatorKey);
487  }
488  lua_setmetatable(L, -2);
489  return 1;
490 }
491 
493 {
494  if (game_display_) {
495  return lua_gui2::show_gamestate_inspector(luaW_checkvconfig(L, 1), gamedata(), game_state_);
496  }
497  return 0;
498 }
499 
500 /**
501  * Gets the unit at the given location or with the given id.
502  * - Arg 1: location
503  * OR
504  * - Arg 1: string ID
505  * - Ret 1: full userdata with __index pointing to impl_unit_get and
506  * __newindex pointing to impl_unit_set.
507  */
509 {
510  map_location loc;
511  if(lua_isstring(L, 1) && !lua_isnumber(L, 1)) {
512  std::string id = luaL_checkstring(L, 1);
513  for(const unit& u : units()) {
514  if(u.id() == id) {
515  luaW_pushunit(L, u.underlying_id());
516  return 1;
517  }
518  }
519  return 0;
520  }
521  if(!luaW_tolocation(L, 1, loc)) {
522  return luaL_argerror(L, 1, "expected string or location");
523  }
524  unit_map::const_iterator ui = units().find(loc);
525 
526  if (!ui.valid()) return 0;
527 
528  luaW_pushunit(L, ui->underlying_id());
529  return 1;
530 }
531 
532 /**
533  * Gets the unit displayed in the sidebar.
534  * - Ret 1: full userdata with __index pointing to impl_unit_get and
535  * __newindex pointing to impl_unit_set.
536  */
538 {
539  if (!game_display_) {
540  return 0;
541  }
542 
543  unit_map::const_iterator ui = board().find_visible_unit(
544  game_display_->displayed_unit_hex(),
545  teams()[game_display_->viewing_team()],
546  game_display_->show_everything());
547  if (!ui.valid()) return 0;
548 
549  luaW_pushunit(L, ui->underlying_id());
550  return 1;
551 }
552 
553 /**
554  * Gets all the units matching a given filter.
555  * - Arg 1: optional table containing a filter
556  * - Arg 2: optional location (to find all units that would match on that location)
557  OR unit (to find all units that would match adjacent to that unit)
558  * - Ret 1: table containing full userdata with __index pointing to
559  * impl_unit_get and __newindex pointing to impl_unit_set.
560  */
562 {
563  vconfig filter = luaW_checkvconfig(L, 1, true);
564  unit_filter filt(filter);
565  std::vector<const unit*> units;
566 
567  if(unit* u_adj = luaW_tounit(L, 2)) {
568  if(!u_adj) {
569  return luaL_argerror(L, 2, "unit not found");
570  }
571  units = filt.all_matches_with_unit(*u_adj);
572  } else if(!lua_isnoneornil(L, 2)) {
573  map_location loc;
574  luaW_tolocation(L, 2, loc);
575  if(!loc.valid()) {
576  return luaL_argerror(L, 2, "invalid location");
577  }
578  units = filt.all_matches_at(loc);
579  } else {
580  units = filt.all_matches_on_map();
581  }
582 
583  // Go through all the units while keeping the following stack:
584  // 1: return table, 2: userdata
585  lua_settop(L, 0);
586  lua_newtable(L);
587  int i = 1;
588 
589  for (const unit * ui : units) {
590  luaW_pushunit(L, ui->underlying_id());
591  lua_rawseti(L, 1, i);
592  ++i;
593  }
594  return 1;
595 }
596 
597 /**
598  * Matches a unit against the given filter.
599  * - Arg 1: full userdata.
600  * - Arg 2: table containing a filter
601  * - Arg 3: optional location OR optional "adjacent" unit
602  * - Ret 1: boolean.
603  */
605 {
606  lua_unit& u = *luaW_checkunit_ref(L, 1);
607 
608  vconfig filter = luaW_checkvconfig(L, 2, true);
609 
610  if (filter.null()) {
611  lua_pushboolean(L, true);
612  return 1;
613  }
614 
615  if(unit* u_adj = luaW_tounit(L, 3)) {
616  if(int side = u.on_recall_list()) {
617  WRN_LUA << "wesnoth.units.matches called with a secondary unit (3rd argument), ";
618  WRN_LUA << "but unit to match was on recall list. ";
619  WRN_LUA << "Thus the 3rd argument is ignored.\n";
620  team &t = board().get_team(side);
621  scoped_recall_unit auto_store("this_unit", t.save_id_or_number(), t.recall_list().find_index(u->id()));
622  lua_pushboolean(L, unit_filter(filter).matches(*u, map_location()));
623  return 1;
624  }
625  if (!u_adj) {
626  return luaL_argerror(L, 3, "unit not found");
627  }
628  lua_pushboolean(L, unit_filter(filter).matches(*u, *u_adj));
629  } else if(int side = u.on_recall_list()) {
630  map_location loc;
631  luaW_tolocation(L, 3, loc); // If argument 3 isn't a location, loc is unchanged
632  team &t = board().get_team(side);
633  scoped_recall_unit auto_store("this_unit", t.save_id_or_number(), t.recall_list().find_index(u->id()));
634  lua_pushboolean(L, unit_filter(filter).matches(*u, loc));
635  return 1;
636  } else {
637  map_location loc = u->get_location();
638  luaW_tolocation(L, 3, loc); // If argument 3 isn't a location, loc is unchanged
639  lua_pushboolean(L, unit_filter(filter).matches(*u, loc));
640  }
641  return 1;
642 }
643 
644 /**
645  * Gets the numeric ids of all the units matching a given filter on the recall lists.
646  * - Arg 1: optional table containing a filter
647  * - Ret 1: table containing full userdata with __index pointing to
648  * impl_unit_get and __newindex pointing to impl_unit_set.
649  */
651 {
652  vconfig filter = luaW_checkvconfig(L, 1, true);
653 
654  // Go through all the units while keeping the following stack:
655  // 1: return table, 2: userdata
656  lua_settop(L, 0);
657  lua_newtable(L);
658  int i = 1, s = 1;
659  const unit_filter ufilt(filter);
660  for (team &t : teams())
661  {
662  for (unit_ptr & u : t.recall_list())
663  {
664  if (!filter.null()) {
665  scoped_recall_unit auto_store("this_unit",
666  t.save_id_or_number(), t.recall_list().find_index(u->id()));
667  if (!ufilt( *u, map_location() ))
668  continue;
669  }
670  luaW_pushunit(L, s, u->underlying_id());
671  lua_rawseti(L, 1, i);
672  ++i;
673  }
674  ++s;
675  }
676  return 1;
677 }
678 
679 /**
680  * Fires an event.
681  * - Arg 1: string containing the event name or id.
682  * - Arg 2: optional first location.
683  * - Arg 3: optional second location.
684  * - Arg 4: optional WML table used as the [weapon] tag.
685  * - Arg 5: optional WML table used as the [second_weapon] tag.
686  * - Ret 1: boolean indicating whether the event was processed or not.
687  */
689 {
690  char const *m = luaL_checkstring(L, 1);
691 
692  int pos = 2;
693  map_location l1, l2;
694  config data;
695 
696  if (luaW_tolocation(L, 2, l1)) {
697  if (luaW_tolocation(L, 3, l2)) {
698  pos = 4;
699  } else {
700  pos = 3;
701  }
702  }
703 
704  if (!lua_isnoneornil(L, pos)) {
705  data.add_child("first", luaW_checkconfig(L, pos));
706  }
707  ++pos;
708  if (!lua_isnoneornil(L, pos)) {
709  data.add_child("second", luaW_checkconfig(L, pos));
710  }
711 
712  bool b = false;
713 
714  if (by_id) {
715  b = std::get<0>(play_controller_.pump().fire("", m, l1, l2, data));
716  }
717  else {
718  b = std::get<0>(play_controller_.pump().fire(m, l1, l2, data));
719  }
720  lua_pushboolean(L, b);
721  return 1;
722 }
723 
724 
725 /**
726  * Fires a wml menu item.
727  * - Arg 1: id of the item. it is not possible to fire items that don't have ids with this function.
728  * - Arg 2: optional first location.
729  * - Ret 1: boolean, true indicating that the event was fired successfully
730  *
731  * NOTE: This is not an "official" feature, it may currently cause assertion failures if used with
732  * menu items which have "needs_select". It is not supported right now to use it this way.
733  * The purpose of this function right now is to make it possible to have automated sanity tests for
734  * the wml menu items system.
735  */
737 {
738  char const *m = luaL_checkstring(L, 1);
739 
740  map_location l1 = luaW_checklocation(L, 2);
741 
742  bool b = game_state_.get_wml_menu_items().fire_item(m, l1, gamedata(), game_state_, units());
743  lua_pushboolean(L, b);
744  return 1;
745 }
746 
747 /**
748  * Gets a WML variable.
749  * - Arg 1: string containing the variable name.
750  * - Arg 2: optional bool indicating if tables for containers should be left empty.
751  * - Ret 1: value of the variable, if any.
752  */
754 {
755  char const *m = luaL_checkstring(L, 1);
757  return luaW_pushvariable(L, v) ? 1 : 0;
758 }
759 
760 /**
761  * Sets a WML variable.
762  * - Arg 1: string containing the variable name.
763  * - Arg 2: boolean/integer/string/table containing the value.
764  */
766 {
767  const std::string m = luaL_checkstring(L, 1);
768  if(m.empty()) return luaL_argerror(L, 1, "empty variable name");
769  if (lua_isnoneornil(L, 2)) {
771  return 0;
772  }
774  luaW_checkvariable(L, v, 2);
775  return 0;
776 }
777 
778 
780 {
781  config cfg = luaW_checkconfig(L, 1);
782  game_state_.add_side_wml(cfg);
783 
784  return 0;
785 }
786 
788 {
789  game_state_.get_wml_menu_items().set_item(luaL_checkstring(L, 1), luaW_checkvconfig(L,2));
790  return 0;
791 }
792 
794 {
795  std::string ids(luaL_checkstring(L, 1));
796  for(const std::string& id : utils::split(ids, ',', utils::STRIP_SPACES)) {
797  if(id.empty()) {
798  WRN_LUA << "[clear_menu_item] has been given an empty id=, ignoring" << std::endl;
799  continue;
800  }
801  game_state_.get_wml_menu_items().erase(id);
802  }
803  return 0;
804 }
805 
807 {
808  game_classification &classification = play_controller_.get_classification();
809  classification.end_credits = luaW_toboolean(L, 1);
810  return 0;
811 }
812 
814 {
815  game_classification &classification = play_controller_.get_classification();
816  classification.end_text = luaW_checktstring(L, 1);
817  if (lua_isnumber(L, 2)) {
818  classification.end_text_duration = static_cast<int> (lua_tonumber(L, 2));
819  }
820 
821  return 0;
822 }
823 
825 {
826  deprecated_message("wesnoth.set_next_scenario", DEP_LEVEL::INDEFINITE, "");
828  return 0;
829 }
830 
831 int game_lua_kernel::intf_shroud_op(lua_State *L, bool place_shroud)
832 {
833 
834  int side_num = luaL_checkinteger(L, 1);
835 
836  if(lua_isstring(L, 2)) {
837  std::string data = lua_tostring(L, 2);
838  // Special case - using a shroud_data string, or "all"
839  team& side = board().get_team(side_num);
840  if(place_shroud) {
841  side.reshroud();
842  }
843  if(data != "all") {
844  side.merge_shroud_map_data(data);
845  } else if(!place_shroud) {
846  bool was_shrouded = side.uses_shroud();
847  side.set_shroud(false);
848  actions::clear_shroud(side.side());
849  side.set_shroud(was_shrouded);
850  }
851  return 0;
852  } else if(lua_istable(L, 2)) {
853  std::vector<map_location> locs_v = lua_check<std::vector<map_location>>(L, 2);
854  std::set<map_location> locs(locs_v.begin(), locs_v.end());
855  team &t = board().get_team(side_num);
856 
857  for (const map_location& loc : locs)
858  {
859  if (place_shroud) {
860  t.place_shroud(loc);
861  } else {
862  t.clear_shroud(loc);
863  }
864  }
865  } else {
866  return luaL_argerror(L, 2, "expected list of locations or shroud data string");
867  }
868 
869  game_display_->labels().recalculate_shroud();
870  game_display_->recalculate_minimap();
871  game_display_->invalidate_all();
872 
873  return 0;
874 }
875 
876 
877 /**
878  * Highlights the given location on the map.
879  * - Arg 1: location.
880  */
882 {
883  if (!game_display_) {
884  return 0;
885  }
886 
887  const map_location loc = luaW_checklocation(L, 1);
888  if(!map().on_board(loc)) return luaL_argerror(L, 1, "not on board");
889  game_display_->highlight_hex(loc);
890  game_display_->display_unit_hex(loc);
891 
892  return 0;
893 }
894 
895 /**
896  * Returns whether the first side is an enemy of the second one.
897  * - Args 1,2: side numbers.
898  * - Ret 1: boolean.
899  */
901 {
902  unsigned side_1, side_2;
903  if(team* t = luaW_toteam(L, 1)) {
904  side_1 = t->side();
905  } else {
906  side_1 = luaL_checkinteger(L, 1);
907  }
908  if(team* t = luaW_toteam(L, 2)) {
909  side_2 = t->side();
910  } else {
911  side_2 = luaL_checkinteger(L, 2);
912  }
913  if (side_1 > teams().size() || side_2 > teams().size()) return 0;
914  lua_pushboolean(L, board().get_team(side_1).is_enemy(side_2));
915  return 1;
916 }
917 
918 /**
919  * Gets whether gamemap scrolling is disabled for the user.
920  * - Ret 1: boolean.
921  */
923 {
924  if (!game_display_) {
925  return 0;
926  }
927 
928  lua_pushboolean(L, game_display_->view_locked());
929  return 1;
930 }
931 
932 /**
933  * Sets whether gamemap scrolling is disabled for the user.
934  * - Arg 1: boolean, specifying the new locked/unlocked status.
935  */
937 {
938  bool lock = luaW_toboolean(L, 1);
939  if (game_display_) {
940  game_display_->set_view_locked(lock);
941  }
942  return 0;
943 }
944 
945 /**
946  * Gets a terrain code.
947  * - Arg 1: map location.
948  * - Ret 1: string.
949  */
951 {
952  map_location loc = luaW_checklocation(L, 1);
953 
954  const t_translation::terrain_code& t = board().map().
955  get_terrain(loc);
957  return 1;
958 }
959 
960 /**
961  * Sets a terrain code.
962  * - Arg 1: map location.
963  * - Arg 2: terrain code string.
964  * - Arg 3: layer: (overlay|base|both, default=both)
965  * - Arg 4: replace_if_failed, default = no
966  */
968 {
969  map_location loc = luaW_checklocation(L, 1);
970  std::string t_str(luaL_checkstring(L, 2));
971 
972  std::string mode_str = "both";
973  bool replace_if_failed = false;
974  if (!lua_isnone(L, 3)) {
975  if (!lua_isnil(L, 3)) {
976  mode_str = luaL_checkstring(L, 3);
977  }
978 
979  if(!lua_isnoneornil(L, 4)) {
980  replace_if_failed = luaW_toboolean(L, 4);
981  }
982  }
983 
984  bool result = board().change_terrain(loc, t_str, mode_str, replace_if_failed);
985 
986  if (game_display_) {
987  game_display_->needs_rebuild(result);
988  }
989 
990  return 0;
991 }
992 
993 /**
994  * Reaplces part of the map.
995  * - Arg 1: map location.
996  * - Arg 2: map data string.
997  * - Arg 3: table for optional named arguments
998  * - is_odd: boolen, if Arg2 has the odd mapo format (as if it was cut from a odd map location)
999  * - ignore_special_locations: boolean
1000  * - rules: table of tables
1001 */
1003 {
1004  map_location loc = luaW_checklocation(L, 1);
1005  std::string t_str(luaL_checkstring(L, 2));
1006  bool is_odd = false;
1007  bool ignore_special_locations = false;
1008  std::vector<gamemap::overlay_rule> rules;
1009 
1010  if(lua_istable(L, 3)) {
1011  if(luaW_tableget(L, 3, "is_odd")) {
1012  is_odd = luaW_toboolean(L, -1);
1013  lua_pop(L, 1);
1014  }
1015  if(luaW_tableget(L, 3, "ignore_special_locations")) {
1016  ignore_special_locations = luaW_toboolean(L, -1);
1017  lua_pop(L, 1);
1018  }
1019  if(luaW_tableget(L, 3, "rules")) {
1020  //todo: reduce code dublication by using read_rules_vector.
1021  if(!lua_istable(L, -1)) {
1022  return luaL_argerror(L, 3, "rules must be a table");
1023  }
1024 
1025  for (int i = 1, i_end = lua_rawlen(L, -1); i <= i_end; ++i)
1026  {
1027  lua_rawgeti(L, -1, i);
1028  if(!lua_istable(L, -1)) {
1029  return luaL_argerror(L, 3, "rules must be a table of tables");
1030  }
1031  rules.push_back(gamemap::overlay_rule());
1032  auto& rule = rules.back();
1033  if(luaW_tableget(L, -1, "old")) {
1034  rule.old_ = t_translation::read_list(luaW_tostring(L, -1));
1035  lua_pop(L, 1);
1036  }
1037 
1038  if(luaW_tableget(L, -1, "new")) {
1039  rule.new_ = t_translation::read_list(luaW_tostring(L, -1));
1040  lua_pop(L, 1);
1041  }
1042 
1043  if(luaW_tableget(L, -1, "mode")) {
1044  auto str = luaW_tostring(L, -1);
1045  rule.mode_ = str == "base" ? terrain_type_data::BASE : (str == "overlay" ? terrain_type_data::OVERLAY : terrain_type_data::BOTH);
1046  lua_pop(L, 1);
1047  }
1048 
1049  if(luaW_tableget(L, -1, "terrain")) {
1051  if(!terrain.empty()) {
1052  rule.terrain_ = terrain[0];
1053  }
1054  lua_pop(L, 1);
1055  }
1056 
1057  if(luaW_tableget(L, -1, "use_old")) {
1058  rule.use_old_ = luaW_toboolean(L, -1);
1059  lua_pop(L, 1);
1060  }
1061 
1062  if(luaW_tableget(L, -1, "replace_if_failed")) {
1063  rule.replace_if_failed_ = luaW_toboolean(L, -1);
1064  lua_pop(L, 1);
1065  }
1066 
1067  lua_pop(L, 1);
1068  }
1069  lua_pop(L, 1);
1070  }
1071  }
1072 
1073 
1074  gamemap mask_map(board().map().tdata(), "");
1075  mask_map.read(t_str, false);
1076  board().map_->overlay(mask_map, loc, rules, is_odd, ignore_special_locations);
1077 
1078  for(team& t : board().teams()) {
1079  t.fix_villages(board().map());
1080  }
1081 
1082  if (game_display_) {
1083  game_display_->needs_rebuild(true);
1084  }
1085 
1086  return 0;
1087 }
1088 
1089 /**
1090  * Gets details about a terrain.
1091  * - Arg 1: terrain code string.
1092  * - Ret 1: table.
1093  */
1095 {
1096  char const *m = luaL_checkstring(L, 1);
1098  if (t == t_translation::NONE_TERRAIN) return 0;
1099  const terrain_type& info = board().map().tdata()->get_terrain_info(t);
1100 
1101  lua_newtable(L);
1102  lua_pushstring(L, info.id().c_str());
1103  lua_setfield(L, -2, "id");
1104  luaW_pushtstring(L, info.name());
1105  lua_setfield(L, -2, "name");
1106  luaW_pushtstring(L, info.editor_name());
1107  lua_setfield(L, -2, "editor_name");
1108  luaW_pushtstring(L, info.description());
1109  lua_setfield(L, -2, "description");
1110  lua_push(L, info.icon_image());
1111  lua_setfield(L, -2, "icon");
1112  lua_push(L, info.editor_image());
1113  lua_setfield(L, -2, "editor_image");
1114  lua_pushinteger(L, info.light_bonus(0));
1115  lua_setfield(L, -2, "light");
1116  lua_pushboolean(L, info.is_village());
1117  lua_setfield(L, -2, "village");
1118  lua_pushboolean(L, info.is_castle());
1119  lua_setfield(L, -2, "castle");
1120  lua_pushboolean(L, info.is_keep());
1121  lua_setfield(L, -2, "keep");
1122  lua_pushinteger(L, info.gives_healing());
1123  lua_setfield(L, -2, "healing");
1124 
1125  return 1;
1126 }
1127 
1128 /**
1129  * Gets time of day information.
1130  * - Arg 1: optional turn number
1131  * - Arg 2: optional location
1132  * - Arg 3: optional boolean (consider_illuminates)
1133  * - Ret 1: table.
1134  */
1136 {
1137  unsigned arg = 1;
1138 
1139  int for_turn = tod_man().turn();
1140  map_location loc = map_location();
1141  bool consider_illuminates = false;
1142 
1143  if(lua_isnumber(L, arg)) {
1144  ++arg;
1145  for_turn = luaL_checkinteger(L, 1);
1146  int number_of_turns = tod_man().number_of_turns();
1147  if(for_turn < 1 || (number_of_turns != -1 && for_turn > number_of_turns)) {
1148  return luaL_argerror(L, 1, "turn number out of range");
1149  }
1150  }
1151  else if(lua_isnil(L, arg)) ++arg;
1152 
1153  if(luaW_tolocation(L, arg, loc)) {
1154  if(!board().map().on_board(loc)) return luaL_argerror(L, arg, "coordinates are not on board");
1155 
1156  if(lua_istable(L, arg)) {
1157  lua_rawgeti(L, arg, 3);
1158  consider_illuminates = luaW_toboolean(L, -1);
1159  lua_pop(L, 1);
1160  } else if(lua_isboolean(L, arg + 1)) {
1161  consider_illuminates = luaW_toboolean(L, arg + 1);
1162  }
1163  }
1164 
1165  const time_of_day& tod = consider_illuminates ?
1166  tod_man().get_illuminated_time_of_day(board().units(), board().map(), loc, for_turn) :
1167  tod_man().get_time_of_day(loc, for_turn);
1168 
1169  lua_newtable(L);
1170  lua_pushstring(L, tod.id.c_str());
1171  lua_setfield(L, -2, "id");
1172  lua_pushinteger(L, tod.lawful_bonus);
1173  lua_setfield(L, -2, "lawful_bonus");
1175  lua_setfield(L, -2, "bonus_modified");
1176  lua_pushstring(L, tod.image.c_str());
1177  lua_setfield(L, -2, "image");
1178  luaW_pushtstring(L, tod.name);
1179  lua_setfield(L, -2, "name");
1180 
1181  lua_pushinteger(L, tod.color.r);
1182  lua_setfield(L, -2, "red");
1183  lua_pushinteger(L, tod.color.g);
1184  lua_setfield(L, -2, "green");
1185  lua_pushinteger(L, tod.color.b);
1186  lua_setfield(L, -2, "blue");
1187 
1188  return 1;
1189 }
1190 
1191 /**
1192  * Gets the max liminal bonus
1193  * - Ret 1: integer.
1194  */
1196 {
1197  int bonus = tod_man().get_max_liminal_bonus();
1198  lua_pushinteger(L, bonus);
1199 
1200  return 1;
1201 }
1202 
1203 /**
1204  * Gets the side of a village owner.
1205  * - Arg 1: map location.
1206  * - Ret 1: integer.
1207  */
1209 {
1210  map_location loc = luaW_checklocation(L, 1);
1211  if (!board().map().is_village(loc))
1212  return 0;
1213 
1214  int side = board().village_owner(loc);
1215  if (!side) return 0;
1216  lua_pushinteger(L, side);
1217  return 1;
1218 }
1219 
1220 /**
1221  * Sets the owner of a village.
1222  * - Arg 1: map location.
1223  * - Arg 2: integer for the side or empty to remove ownership.
1224  */
1226 {
1227  map_location loc = luaW_checklocation(L, 1);
1228  if(!board().map().is_village(loc)) {
1229  return 0;
1230  }
1231 
1232  const int old_side_num = board().village_owner(loc);
1233  const int new_side_num = lua_isnoneornil(L, 2) ? 0 : luaL_checkinteger(L, 2);
1234 
1235  team* old_side = nullptr;
1236  team* new_side = nullptr;
1237 
1238  if(old_side_num == new_side_num) {
1239  return 0;
1240  }
1241 
1242  try {
1243  old_side = &board().get_team(old_side_num);
1244  } catch(const std::out_of_range&) {
1245  // old_side_num is invalid, most likely because the village wasn't captured.
1246  old_side = nullptr;
1247  }
1248 
1249  try {
1250  new_side = &board().get_team(new_side_num);
1251  } catch(const std::out_of_range&) {
1252  // new_side_num is invalid.
1253  new_side = nullptr;
1254  }
1255 
1256  // The new side was valid, but already defeated. Do nothing.
1257  if(new_side && board().team_is_defeated(*new_side)) {
1258  return 0;
1259  }
1260 
1261  // Even if the new side is not valid, we still want to remove the village from the old side.
1262  // This covers the case where new_side_num equals 0. The behavior in that case is to simply
1263  // un-assign the village from the old side, which of course we also want to happen if the new
1264  // side IS valid. If the village in question hadn't been captured, this won't fire (old_side
1265  // will be a nullptr).
1266  if(old_side) {
1267  old_side->lose_village(loc);
1268  }
1269 
1270  // If the new side was valid, re-assign the village.
1271  if(new_side) {
1272  new_side->get_village(loc, old_side_num, (luaW_toboolean(L, 3) ? &gamedata() : nullptr));
1273  }
1274 
1275  return 0;
1276 }
1277 
1278 
1279 /**
1280  * Returns the map size.
1281  * - Ret 1: width.
1282  * - Ret 2: height.
1283  * - Ret 3: border size.
1284  */
1286 {
1287  const gamemap &map = board().map();
1288  lua_pushinteger(L, map.w());
1289  lua_pushinteger(L, map.h());
1290  lua_pushinteger(L, map.border_size());
1291  return 3;
1292 }
1293 
1294 /**
1295  * Returns the currently overed tile.
1296  * - Ret 1: x.
1297  * - Ret 2: y.
1298  */
1300 {
1301  if (!game_display_) {
1302  return 0;
1303  }
1304 
1305  const map_location &loc = game_display_->mouseover_hex();
1306  if (!board().map().on_board(loc)) return 0;
1307  lua_pushinteger(L, loc.wml_x());
1308  lua_pushinteger(L, loc.wml_y());
1309  return 2;
1310 }
1311 
1312 /**
1313  * Returns the currently selected tile.
1314  * - Ret 1: x.
1315  * - Ret 2: y.
1316  */
1318 {
1319  if (!game_display_) {
1320  return 0;
1321  }
1322 
1323  const map_location &loc = game_display_->selected_hex();
1324  if (!board().map().on_board(loc)) return 0;
1325  lua_pushinteger(L, loc.wml_x());
1326  lua_pushinteger(L, loc.wml_y());
1327  return 2;
1328 }
1329 
1330 
1331 /**
1332  * Gets a table for an resource tag.
1333  * - Arg 1: userdata (ignored).
1334  * - Arg 2: string containing id of the desired resource
1335  * - Ret 1: config for the era
1336  */
1338 {
1339  std::string m = luaL_checkstring(L, 1);
1340  if(const config& res = game_config_manager::get()->game_config().find_child("resource","id",m)) {
1341  luaW_pushconfig(L, res);
1342  return 1;
1343  }
1344  else {
1345  return luaL_argerror(L, 1, ("Cannot find ressource with id '" + m + "'").c_str());
1346  }
1347 }
1348 
1349 /**
1350  * Gets a table for an era tag.
1351  * - Arg 1: userdata (ignored).
1352  * - Arg 2: string containing id of the desired era
1353  * - Ret 1: config for the era
1354  */
1355 static int intf_get_era(lua_State *L)
1356 {
1357  char const *m = luaL_checkstring(L, 1);
1358  luaW_pushconfig(L, game_config_manager::get()->game_config().find_child("era","id",m));
1359  return 1;
1360 }
1361 
1362 /**
1363  * Gets some game_config data (__index metamethod).
1364  * - Arg 1: userdata (ignored).
1365  * - Arg 2: string containing the name of the property.
1366  * - Ret 1: something containing the attribute.
1367  */
1369 {
1370  LOG_LUA << "impl_game_config_get\n";
1371  char const *m = luaL_checkstring(L, 2);
1372 
1373  // Find the corresponding attribute.
1374  return_int_attrib("last_turn", tod_man().number_of_turns());
1375  return_bool_attrib("do_healing", play_controller_.gamestate().do_healing_);
1376  return_string_attrib("next_scenario", gamedata().next_scenario());
1377  return_string_attrib("theme", gamedata().get_theme());
1378  return_string_attrib("scenario_id", gamedata().get_id());
1379  return_vector_string_attrib("defeat_music", gamedata().get_defeat_music());
1380  return_vector_string_attrib("victory_music", gamedata().get_victory_music());
1381  return_vector_string_attrib("active_resources", utils::split(play_controller_.get_loaded_resources()) );
1382 
1383  const mp_game_settings& mp_settings = play_controller_.get_mp_settings();
1384  const game_classification & classification = play_controller_.get_classification();
1385 
1386  return_string_attrib("campaign_type", classification.campaign_type.to_string());
1387  if(classification.campaign_type==game_classification::CAMPAIGN_TYPE::MULTIPLAYER) {
1388  return_cfgref_attrib("mp_settings", mp_settings.to_config());
1389  return_cfgref_attrib("era", game_config_manager::get()->game_config().find_child("era","id",classification.era_id));
1390  //^ finds the era with name matching mp_era, and creates a lua reference from the config of that era.
1391 
1392  //This code for SigurdFD, not the cleanest implementation but seems to work just fine.
1393  std::vector<std::string> eras_list;
1394  for (const config& era : game_config_manager::get()->game_config().child_range("era") ) {
1395  eras_list.push_back(era["id"].str());
1396  }
1397  return_string_attrib("eras", utils::join(eras_list));
1398  }
1400 }
1401 
1402 /**
1403  * Sets some game_config data (__newindex metamethod).
1404  * - Arg 1: userdata (ignored).
1405  * - Arg 2: string containing the name of the property.
1406  * - Arg 3: something containing the attribute.
1407  */
1409 {
1410  LOG_LUA << "impl_game_config_set\n";
1411  char const *m = luaL_checkstring(L, 2);
1412 
1413  // Find the corresponding attribute.
1414  modify_int_attrib("base_income", game_config::base_income = value);
1415  modify_int_attrib("village_income", game_config::village_income = value);
1416  modify_int_attrib("village_support", game_config::village_support = value);
1417  modify_int_attrib("poison_amount", game_config::poison_amount = value);
1418  modify_int_attrib("rest_heal_amount", game_config::rest_heal_amount = value);
1419  modify_int_attrib("recall_cost", game_config::recall_cost = value);
1420  modify_int_attrib("kill_experience", game_config::kill_experience = value);
1421  modify_int_attrib("combat_experience", game_config::combat_experience = value);
1422  modify_int_attrib("last_turn", tod_man().set_number_of_turns_by_wml(value));
1423  modify_bool_attrib("do_healing", play_controller_.gamestate().do_healing_ = value);
1424  modify_string_attrib("next_scenario", gamedata().set_next_scenario(value));
1425  modify_string_attrib("theme",
1426  gamedata().set_theme(value);
1428  game_display_->set_theme(play_controller_.get_theme(game_config, value));
1429  );
1430  modify_vector_string_attrib("defeat_music", gamedata().set_defeat_music(std::move(value)));
1431  modify_vector_string_attrib("victory_music", gamedata().set_victory_music(std::move(value)));
1433 }
1434 
1435 /**
1436  converts synced_context::get_synced_state() to a string.
1437 */
1439 {
1440  //maybe return "initial" for game_data::INITIAL?
1441  if(gamedata().phase() == game_data::PRELOAD || gamedata().phase() == game_data::INITIAL)
1442  {
1443  return "preload";
1444  }
1446  {
1448  return "local_choice";
1450  return "synced";
1452  return "unsynced";
1453  default:
1454  throw game::game_error("Found corrupt synced_context::synced_state");
1455  }
1456 }
1457 
1458 
1459 /**
1460  * Gets some data about current point of game (__index metamethod).
1461  * - Arg 1: userdata (ignored).
1462  * - Arg 2: string containing the name of the property.
1463  * - Ret 1: something containing the attribute.
1464  */
1466 {
1467  char const *m = luaL_checkstring(L, 2);
1468 
1469  // Find the corresponding attribute.
1470  return_int_attrib("side", play_controller_.current_side());
1471  return_int_attrib("turn", play_controller_.turn());
1472  return_string_attrib("synced_state", synced_state());
1473  return_bool_attrib("user_can_invoke_commands", !play_controller_.is_lingering() && play_controller_.gamestate().init_side_done() && !events::commands_disabled && gamedata().phase() == game_data::PLAY);
1474 
1475  if (strcmp(m, "event_context") == 0)
1476  {
1477  const game_events::queued_event &ev = get_event_info();
1478  config cfg;
1479  cfg["name"] = ev.name;
1480  cfg["id"] = ev.id;
1481  if (const config &weapon = ev.data.child("first")) {
1482  cfg.add_child("weapon", weapon);
1483  }
1484  if (const config &weapon = ev.data.child("second")) {
1485  cfg.add_child("second_weapon", weapon);
1486  }
1487 
1488  const config::attribute_value di = ev.data["damage_inflicted"];
1489  if(!di.empty()) {
1490  cfg["damage_inflicted"] = di;
1491  }
1492 
1493  if (ev.loc1.valid()) {
1494  cfg["x1"] = ev.loc1.filter_loc().wml_x();
1495  cfg["y1"] = ev.loc1.filter_loc().wml_y();
1496  // The position of the unit involved in this event, currently the only case where this is different from x1/y1 are enter/exit_hex events
1497  cfg["unit_x"] = ev.loc1.wml_x();
1498  cfg["unit_y"] = ev.loc1.wml_y();
1499  }
1500  if (ev.loc2.valid()) {
1501  cfg["x2"] = ev.loc2.filter_loc().wml_x();
1502  cfg["y2"] = ev.loc2.filter_loc().wml_y();
1503  }
1504  luaW_pushconfig(L, cfg);
1505  return 1;
1506  }
1507 
1508  return 0;
1509 }
1510 
1511 /**
1512  * Displays a message in the chat window and in the logs.
1513  * - Arg 1: optional message header.
1514  * - Arg 2 (or 1): message.
1515  */
1517 {
1518  t_string m = luaW_checktstring(L, 1);
1519  t_string h = m;
1520  if (lua_isnone(L, 2)) {
1521  h = "Lua";
1522  } else {
1523  m = luaW_checktstring(L, 2);
1524  }
1525  lua_chat(h, m);
1526  LOG_LUA << "Script says: \"" << m << "\"\n";
1527  return 0;
1528 }
1529 
1531 {
1532  if (game_display_) {
1534  }
1535  return 0;
1536 }
1537 
1539 {
1540  if(!game_display_) {
1541  return 0;
1542  }
1543  double factor = luaL_checknumber(L, 1);
1544  bool relative = luaW_toboolean(L, 2);
1545  if(relative) {
1546  factor *= game_display_->get_zoom_factor();
1547  }
1548  // Passing true explicitly to avoid casting to int.
1549  // Without doing one of the two, the call is ambiguous.
1550  game_display_->set_zoom(factor * game_config::tile_size, true);
1551  lua_pushnumber(L, game_display_->get_zoom_factor());
1552  return 1;
1553 }
1554 
1555 /**
1556  * Removes all messages from the chat window.
1557  */
1559 {
1560  if (game_display_) {
1561  game_display_->get_chat_manager().clear_chat_messages();
1562  }
1563  return 0;
1564 }
1565 
1567 {
1568  const end_level_data& data = *static_cast<end_level_data*>(lua_touserdata(L, 1));
1569  const char* m = luaL_checkstring(L, 2);
1570 
1571  return_bool_attrib("linger_mode", data.transient.linger_mode);
1572  return_bool_attrib("reveal_map", data.transient.reveal_map);
1573  return_bool_attrib("carryover_report", data.transient.carryover_report);
1574  return_bool_attrib("prescenario_save", data.prescenario_save);
1575  return_bool_attrib("replay_save", data.replay_save);
1576  return_bool_attrib("proceed_to_next_level", data.proceed_to_next_level);
1577  return_bool_attrib("is_victory", data.is_victory);
1578  return_bool_attrib("is_loss", !data.is_victory);
1579  return_cstring_attrib("result", data.is_victory ? "victory" : "loss"); // to match wesnoth.end_level()
1580  return_string_attrib("test_result", data.test_result);
1581  return_cfg_attrib("__cfg", data.to_config_full());
1582 
1583  return 0;
1584 }
1585 
1586 namespace {
1587  struct end_level_committer {
1588  end_level_committer(end_level_data& data, play_controller& pc) : data_(data), pc_(pc) {}
1589  ~end_level_committer() {
1590  pc_.set_end_level_data(data_);
1591  }
1592  private:
1593  end_level_data& data_;
1594  play_controller& pc_;
1595  };
1596 }
1597 
1599 {
1600  end_level_data& data = *static_cast<end_level_data*>(lua_touserdata(L, 1));
1601  const char* m = luaL_checkstring(L, 2);
1602  end_level_committer commit(data, play_controller_);
1603 
1604  modify_bool_attrib("linger_mode", data.transient.linger_mode = value);
1605  modify_bool_attrib("reveal_map", data.transient.reveal_map = value);
1606  modify_bool_attrib("carryover_report", data.transient.carryover_report = value);
1607  modify_bool_attrib("prescenario_save", data.prescenario_save = value);
1608  modify_bool_attrib("replay_save", data.replay_save = value);
1609  modify_string_attrib("test_result", data.test_result = value);
1610 
1611  return 0;
1612 }
1613 
1615 {
1616  end_level_data* data = static_cast<end_level_data*>(lua_touserdata(L, 1));
1617  UNUSED(data); // Suppress an erroneous MSVC warning (a destructor call doesn't count as a reference)
1618  data->~end_level_data();
1619  return 0;
1620 }
1621 
1623 {
1624  if (!play_controller_.is_regular_game_end()) {
1625  return 0;
1626  }
1627  auto data = play_controller_.get_end_level_data_const();
1628  new(L) end_level_data(data);
1629  if(luaL_newmetatable(L, "end level data")) {
1630  static luaL_Reg const callbacks[] {
1631  { "__index", &impl_end_level_data_get},
1632  { "__newindex", &dispatch<&game_lua_kernel::impl_end_level_data_set>},
1633  { "__gc", &impl_end_level_data_collect},
1634  { nullptr, nullptr }
1635  };
1636  luaL_setfuncs(L, callbacks, 0);
1637  }
1638  lua_setmetatable(L, -2);
1639  return 1;
1640 }
1641 
1643 {
1644  vconfig cfg(luaW_checkvconfig(L, 1));
1646 
1647  data.proceed_to_next_level = cfg["proceed_to_next_level"].to_bool(true);
1648  data.transient.carryover_report = cfg["carryover_report"].to_bool(true);
1649  data.prescenario_save = cfg["save"].to_bool(true);
1650  data.replay_save = cfg["replay_save"].to_bool(true);
1651  data.transient.linger_mode = cfg["linger_mode"].to_bool(true) && !teams().empty();
1652  data.transient.reveal_map = cfg["reveal_map"].to_bool(true);
1653  data.is_victory = cfg["result"] == "victory";
1654  data.test_result = cfg["test_result"].str(LEVEL_RESULT::enum_to_string(LEVEL_RESULT::TEST_NOT_SET));
1655  play_controller_.set_end_level_data(data);
1656  return 0;
1657 }
1658 
1660 {
1661  //note that next_player_number = 1, next_player_number = nteams+1 both set the next team to be the first team
1662  //but the later will make the turn counter change aswell fire turn end events accoringly etc.
1663  if (!lua_isnoneornil(L, 1)) {
1664  int npn = luaL_checknumber(L, 1);
1665  if (npn <= 0 /*TODO: || npn > 2*nteams*/) {
1666  return luaL_argerror(L, 1, "side number out of range");
1667  }
1669  }
1670  play_controller_.force_end_turn();
1671  return 0;
1672 }
1673 
1674 /**
1675  * Evaluates a boolean WML conditional.
1676  * - Arg 1: WML table.
1677  * - Ret 1: boolean.
1678  */
1680 {
1681  vconfig cond = luaW_checkvconfig(L, 1);
1682  bool b = game_events::conditional_passed(cond);
1683  lua_pushboolean(L, b);
1684  return 1;
1685 }
1686 
1687 
1688 /**
1689  * Finds a path between two locations.
1690  * - Arg 1: source location. (Or Arg 1: unit.)
1691  * - Arg 2: destination.
1692  * - Arg 3: optional cost function or
1693  * table (optional fields: ignore_units, ignore_teleport, max_cost, viewing_side).
1694  * - Ret 1: array of pairs containing path steps.
1695  * - Ret 2: path cost.
1696  */
1698 {
1699  int arg = 1;
1700  map_location src, dst;
1701  const unit* u = nullptr;
1702 
1703  if (lua_isuserdata(L, arg))
1704  {
1705  u = &luaW_checkunit(L, arg);
1706  src = u->get_location();
1707  ++arg;
1708  }
1709  else
1710  {
1711  src = luaW_checklocation(L, arg);
1712  unit_map::const_unit_iterator ui = units().find(src);
1713  if (ui.valid()) {
1714  u = ui.get_shared_ptr().get();
1715  }
1716  ++arg;
1717  }
1718 
1719  dst = luaW_checklocation(L, arg);
1720  ++arg;
1721 
1722  if (!board().map().on_board(src))
1723  return luaL_argerror(L, 1, "invalid location");
1724  if (!board().map().on_board(dst))
1725  return luaL_argerror(L, arg - 2, "invalid location");
1726 
1727  const gamemap &map = board().map();
1728  int viewing_side = 0;
1729  bool ignore_units = false, see_all = false, ignore_teleport = false;
1730  double stop_at = 10000;
1731  std::unique_ptr<pathfind::cost_calculator> calc;
1732 
1733  if (lua_istable(L, arg))
1734  {
1735  ignore_units = luaW_table_get_def<bool>(L, arg, "ignore_units", false);
1736 
1737  ignore_teleport = luaW_table_get_def<bool>(L, arg, "ignore_teleport", false);
1738 
1739  stop_at = luaW_table_get_def<double>(L, arg, "stop_at", stop_at);
1740 
1741 
1742  lua_pushstring(L, "viewing_side");
1743  lua_rawget(L, arg);
1744  if (!lua_isnil(L, -1)) {
1745  int i = luaL_checkinteger(L, -1);
1746  if (i >= 1 && i <= static_cast<int>(teams().size())) viewing_side = i;
1747  else see_all = true;
1748  }
1749  lua_pop(L, 1);
1750 
1751  lua_pushstring(L, "calculate");
1752  lua_rawget(L, arg);
1753  if(lua_isfunction(L, -1)) {
1754  calc.reset(new lua_pathfind_cost_calculator(L, lua_gettop(L)));
1755  }
1756  // Don't pop, the lua_pathfind_cost_calculator requires it to stay on the stack.
1757  }
1758  else if (lua_isfunction(L, arg))
1759  {
1760  deprecated_message("wesnoth.find_path with cost_function as last argument", DEP_LEVEL::FOR_REMOVAL, {1, 17, 0}, "Use calculate=cost_function inside the path options table instead.");
1761  calc.reset(new lua_pathfind_cost_calculator(L, arg));
1762  }
1763 
1764  const team& viewing_team = viewing_side
1765  ? board().get_team(viewing_side)
1766  : board().get_team(u->side());
1767 
1768  pathfind::teleport_map teleport_locations;
1769 
1770  if(!ignore_teleport) {
1771  teleport_locations = pathfind::get_teleport_locations(*u, viewing_team, see_all, ignore_units);
1772  }
1773 
1774  if (!calc) {
1775  if (!u) return luaL_argerror(L, 1, "unit not found");
1776 
1777  calc.reset(new pathfind::shortest_path_calculator(*u, viewing_team,
1778  teams(), map, ignore_units, false, see_all));
1779  }
1780 
1781  pathfind::plain_route res = pathfind::a_star_search(src, dst, stop_at, *calc, map.w(), map.h(),
1782  &teleport_locations);
1783 
1784  int nb = res.steps.size();
1785  lua_createtable(L, nb, 0);
1786  for (int i = 0; i < nb; ++i)
1787  {
1788  lua_createtable(L, 2, 0);
1789  lua_pushinteger(L, res.steps[i].wml_x());
1790  lua_rawseti(L, -2, 1);
1791  lua_pushinteger(L, res.steps[i].wml_y());
1792  lua_rawseti(L, -2, 2);
1793  lua_rawseti(L, -2, i + 1);
1794  }
1795  lua_pushinteger(L, res.move_cost);
1796 
1797  return 2;
1798 }
1799 
1800 /**
1801  * Finds all the locations reachable by a unit.
1802  * - Arg 1: source location OR unit.
1803  * - Arg 2: optional table (optional fields: ignore_units, ignore_teleport, additional_turns, viewing_side).
1804  * - Ret 1: array of triples (coordinates + remaining movement).
1805  */
1807 {
1808  int arg = 1;
1809  const unit* u = nullptr;
1810 
1811  if (lua_isuserdata(L, arg))
1812  {
1813  u = &luaW_checkunit(L, arg);
1814  ++arg;
1815  }
1816  else
1817  {
1818  map_location src = luaW_checklocation(L, arg);
1819  unit_map::const_unit_iterator ui = units().find(src);
1820  if (!ui.valid())
1821  return luaL_argerror(L, 1, "unit not found");
1822  u = ui.get_shared_ptr().get();
1823  ++arg;
1824  }
1825 
1826  int viewing_side = 0;
1827  bool ignore_units = false, see_all = false, ignore_teleport = false;
1828  int additional_turns = 0;
1829 
1830  if (lua_istable(L, arg))
1831  {
1832  lua_pushstring(L, "ignore_units");
1833  lua_rawget(L, arg);
1834  ignore_units = luaW_toboolean(L, -1);
1835  lua_pop(L, 1);
1836 
1837  lua_pushstring(L, "ignore_teleport");
1838  lua_rawget(L, arg);
1839  ignore_teleport = luaW_toboolean(L, -1);
1840  lua_pop(L, 1);
1841 
1842  lua_pushstring(L, "additional_turns");
1843  lua_rawget(L, arg);
1844  additional_turns = lua_tointeger(L, -1);
1845  lua_pop(L, 1);
1846 
1847  lua_pushstring(L, "viewing_side");
1848  lua_rawget(L, arg);
1849  if (!lua_isnil(L, -1)) {
1850  int i = luaL_checkinteger(L, -1);
1851  if (i >= 1 && i <= static_cast<int>(teams().size())) viewing_side = i;
1852  else see_all = true;
1853  }
1854  lua_pop(L, 1);
1855  }
1856 
1857  const team& viewing_team = viewing_side
1858  ? board().get_team(viewing_side)
1859  : board().get_team(u->side());
1860 
1861  pathfind::paths res(*u, ignore_units, !ignore_teleport,
1862  viewing_team, additional_turns, see_all, ignore_units);
1863 
1864  int nb = res.destinations.size();
1865  lua_createtable(L, nb, 0);
1866  for (int i = 0; i < nb; ++i)
1867  {
1869  lua_createtable(L, 2, 0);
1870  lua_pushinteger(L, s.curr.wml_x());
1871  lua_rawseti(L, -2, 1);
1872  lua_pushinteger(L, s.curr.wml_y());
1873  lua_rawseti(L, -2, 2);
1874  lua_pushinteger(L, s.move_left);
1875  lua_rawseti(L, -2, 3);
1876  lua_rawseti(L, -2, i + 1);
1877  }
1878 
1879  return 1;
1880 }
1881 
1882 static bool intf_find_cost_map_helper(const unit * ptr) {
1883  return ptr->get_location().valid();
1884 }
1885 
1886 template<typename T> // This is only a template so I can avoid typing out the long typename. >_>
1887 static int load_fake_units(lua_State* L, int arg, T& fake_units)
1888 {
1889  for (int i = 1, i_end = lua_rawlen(L, arg); i <= i_end; ++i)
1890  {
1891  map_location src;
1892  lua_rawgeti(L, arg, i);
1893  int entry = lua_gettop(L);
1894  if (!lua_istable(L, entry)) {
1895  goto error;
1896  }
1897 
1898  if (!luaW_tolocation(L, entry, src)) {
1899  goto error;
1900  }
1901 
1902  lua_rawgeti(L, entry, 3);
1903  if (!lua_isnumber(L, -1)) {
1904  lua_getfield(L, entry, "side");
1905  if (!lua_isnumber(L, -1)) {
1906  goto error;
1907  }
1908  }
1909  int side = lua_tointeger(L, -1);
1910 
1911  lua_rawgeti(L, entry, 4);
1912  if (!lua_isstring(L, -1)) {
1913  lua_getfield(L, entry, "type");
1914  if (!lua_isstring(L, -1)) {
1915  goto error;
1916  }
1917  }
1919 
1920  fake_units.emplace_back(src, side, unit_type);
1921 
1922  lua_settop(L, entry - 1);
1923  }
1924  return 0;
1925 error:
1926  return luaL_argerror(L, arg, "unit type table malformed - each entry should be either array of 4 elements or table with keys x, y, side, type");
1927 }
1928 
1929 /**
1930  * Is called with one or more units and builds a cost map.
1931  * - Arg 1: source location. (Or Arg 1: unit. Or Arg 1: table containing a filter)
1932  * - Arg 2: optional array of tables with 4 elements (coordinates + side + unit type string)
1933  * - Arg 3: optional table (optional fields: ignore_units, ignore_teleport, viewing_side, debug).
1934  * - Arg 4: optional table: standard location filter.
1935  * - Ret 1: array of triples (coordinates + array of tuples(summed cost + reach counter)).
1936  */
1938 {
1939  int arg = 1;
1940  unit* unit = luaW_tounit(L, arg, true);
1942  luaW_tovconfig(L, arg, filter);
1943 
1944  std::vector<const ::unit*> real_units;
1945  typedef std::vector<std::tuple<map_location, int, std::string>> unit_type_vector;
1946  unit_type_vector fake_units;
1947 
1948 
1949  if (unit) // 1. arg - unit
1950  {
1951  real_units.push_back(unit);
1952  }
1953  else if (!filter.null()) // 1. arg - filter
1954  {
1955  boost::copy(unit_filter(filter).all_matches_on_map() | boost::adaptors::filtered(&intf_find_cost_map_helper), std::back_inserter(real_units));
1956  }
1957  else // 1. arg - coordinates
1958  {
1959  map_location src = luaW_checklocation(L, arg);
1960  unit_map::const_unit_iterator ui = units().find(src);
1961  if (ui.valid())
1962  {
1963  real_units.push_back(&(*ui));
1964  }
1965  }
1966  ++arg;
1967 
1968  if (lua_istable(L, arg)) // 2. arg - optional types
1969  {
1970  load_fake_units(L, arg, fake_units);
1971  ++arg;
1972  }
1973 
1974  if(real_units.empty() && fake_units.empty())
1975  {
1976  return luaL_argerror(L, 1, "unit(s) not found");
1977  }
1978 
1979  int viewing_side = 0;
1980  bool ignore_units = true, see_all = true, ignore_teleport = false, debug = false, use_max_moves = false;
1981 
1982  if (lua_istable(L, arg)) // 4. arg - options
1983  {
1984  lua_pushstring(L, "ignore_units");
1985  lua_rawget(L, arg);
1986  if (!lua_isnil(L, -1))
1987  {
1988  ignore_units = luaW_toboolean(L, -1);
1989  }
1990  lua_pop(L, 1);
1991 
1992  lua_pushstring(L, "ignore_teleport");
1993  lua_rawget(L, arg);
1994  if (!lua_isnil(L, -1))
1995  {
1996  ignore_teleport = luaW_toboolean(L, -1);
1997  }
1998  lua_pop(L, 1);
1999 
2000  lua_pushstring(L, "viewing_side");
2001  lua_rawget(L, arg);
2002  if (!lua_isnil(L, -1))
2003  {
2004  int i = luaL_checkinteger(L, -1);
2005  if (i >= 1 && i <= static_cast<int>(teams().size()))
2006  {
2007  viewing_side = i;
2008  see_all = false;
2009  }
2010  }
2011 
2012  lua_pushstring(L, "debug");
2013  lua_rawget(L, arg);
2014  if (!lua_isnil(L, -1))
2015  {
2016  debug = luaW_toboolean(L, -1);
2017  }
2018  lua_pop(L, 1);
2019 
2020  lua_pushstring(L, "use_max_moves");
2021  lua_rawget(L, arg);
2022  if (!lua_isnil(L, -1))
2023  {
2024  use_max_moves = luaW_toboolean(L, -1);
2025  }
2026  lua_pop(L, 1);
2027  ++arg;
2028  }
2029 
2030  // 5. arg - location filter
2031  filter = vconfig::unconstructed_vconfig();
2032  std::set<map_location> location_set;
2033  luaW_tovconfig(L, arg, filter);
2034  if (filter.null())
2035  {
2036  filter = vconfig(config(), true);
2037  }
2038  filter_context & fc = game_state_;
2039  const terrain_filter t_filter(filter, &fc);
2040  t_filter.get_locations(location_set, true);
2041  ++arg;
2042 
2043  // build cost_map
2044  const team& viewing_team = viewing_side
2045  ? board().get_team(viewing_side)
2046  : board().teams()[0];
2047 
2048  pathfind::full_cost_map cost_map(
2049  ignore_units, !ignore_teleport, viewing_team, see_all, ignore_units);
2050 
2051  for (const ::unit* const u : real_units)
2052  {
2053  cost_map.add_unit(*u, use_max_moves);
2054  }
2055  for (const unit_type_vector::value_type& fu : fake_units)
2056  {
2057  const unit_type* ut = unit_types.find(std::get<2>(fu));
2058  cost_map.add_unit(std::get<0>(fu), ut, std::get<1>(fu));
2059  }
2060 
2061  if (debug)
2062  {
2063  if (game_display_) {
2064  game_display_->labels().clear_all();
2065  for (const map_location& loc : location_set)
2066  {
2067  std::stringstream s;
2068  s << cost_map.get_pair_at(loc).first;
2069  s << " / ";
2070  s << cost_map.get_pair_at(loc).second;
2071  game_display_->labels().set_label(loc, s.str());
2072  }
2073  }
2074  }
2075 
2076  // create return value
2077  lua_createtable(L, location_set.size(), 0);
2078  int counter = 1;
2079  for (const map_location& loc : location_set)
2080  {
2081  lua_createtable(L, 4, 0);
2082 
2083  lua_pushinteger(L, loc.wml_x());
2084  lua_rawseti(L, -2, 1);
2085 
2086  lua_pushinteger(L, loc.wml_y());
2087  lua_rawseti(L, -2, 2);
2088 
2089  lua_pushinteger(L, cost_map.get_pair_at(loc).first);
2090  lua_rawseti(L, -2, 3);
2091 
2092  lua_pushinteger(L, cost_map.get_pair_at(loc).second);
2093  lua_rawseti(L, -2, 4);
2094 
2095  lua_rawseti(L, -2, counter);
2096  ++counter;
2097  }
2098  return 1;
2099 }
2100 
2102  vconfig cfg(luaW_checkvconfig(L, 1));
2103 
2104  // Remove any old message.
2105  static int floating_label = 0;
2106  if (floating_label)
2107  font::remove_floating_label(floating_label);
2108 
2109  // Display a message on-screen
2110  std::string text = cfg["text"];
2111  if(text.empty() || !game_display_)
2112  return 0;
2113 
2114  int size = cfg["size"].to_int(font::SIZE_SMALL);
2115  int lifetime = cfg["duration"].to_int(50);
2116 
2117  color_t color = font::LABEL_COLOR;
2118 
2119  if(!cfg["color"].empty()) {
2120  color = color_t::from_rgb_string(cfg["color"]);
2121  } else if(cfg.has_attribute("red") || cfg.has_attribute("green") || cfg.has_attribute("blue")) {
2122  color = color_t(cfg["red"], cfg["green"], cfg["blue"]);
2123  }
2124 
2125  const SDL_Rect& rect = game_display_->map_outside_area();
2126 
2127  font::floating_label flabel(text);
2128  flabel.set_font_size(size);
2129  flabel.set_color(color);
2130  flabel.set_position(rect.x + rect.w/2, rect.y + rect.h/2);
2131  flabel.set_lifetime(lifetime);
2132  flabel.set_clip_rect(rect);
2133 
2134  floating_label = font::add_floating_label(flabel);
2135 
2136  return 0;
2137 }
2138 
2140 {
2141  if(game_display_) {
2142  game_display_->invalidate(loc);
2143  }
2144 
2145  units().erase(loc);
2146  resources::whiteboard->on_kill_unit();
2147 }
2148 
2149 /**
2150  * Places a unit on the map.
2151  * - Arg 1: (optional) location.
2152  * - Arg 2: Unit (WML table or proxy), or nothing/nil to delete.
2153  * OR
2154  * - Arg 1: Unit (WML table or proxy)
2155  * - Arg 2: (optional) location
2156  * - Arg 3: (optional) boolean
2157  */
2159 {
2160  if(map_locked_) {
2161  return luaL_error(L, "Attempted to move a unit while the map is locked");
2162  }
2163 
2164  map_location loc;
2165  if (luaW_tolocation(L, 2, loc)) {
2166  if (!map().on_board(loc)) {
2167  return luaL_argerror(L, 2, "invalid location");
2168  }
2169  }
2170 
2171  if((luaW_isunit(L, 1))) {
2172  lua_unit& u = *luaW_checkunit_ref(L, 1);
2173  if(u.on_map() && u->get_location() == loc) {
2174  return 0;
2175  }
2176  if (!loc.valid()) {
2177  loc = u->get_location();
2178  if (!map().on_board(loc))
2179  return luaL_argerror(L, 1, "invalid location");
2180  }
2181 
2182  put_unit_helper(loc);
2183  u.put_map(loc);
2184  u.get_shared()->anim_comp().set_standing();
2185  } else if(!lua_isnoneornil(L, 1)) {
2186  const vconfig* vcfg = nullptr;
2187  config cfg = luaW_checkconfig(L, 1, vcfg);
2188  if (!map().on_board(loc)) {
2189  loc.set_wml_x(cfg["x"]);
2190  loc.set_wml_y(cfg["y"]);
2191  if (!map().on_board(loc))
2192  return luaL_argerror(L, 2, "invalid location");
2193  }
2194 
2195  unit_ptr u = unit::create(cfg, true, vcfg);
2196  put_unit_helper(loc);
2197  u->set_location(loc);
2198  units().insert(u);
2199  }
2200 
2201  // Fire event if using the deprecated version or if the final argument is not false
2202  // If the final boolean argument is omitted, the actual final argument (the unit or location) will always yield true.
2203  if(luaW_toboolean(L, -1)) {
2204  play_controller_.pump().fire("unit_placed", loc);
2205  }
2206  return 0;
2207 }
2208 
2209 /**
2210  * Erases a unit from the map
2211  * - Arg 1: Unit to erase OR Location to erase unit
2212  */
2214 {
2215  if(map_locked_) {
2216  return luaL_error(L, "Attempted to remove a unit while the map is locked");
2217  }
2218  map_location loc;
2219 
2220  if(luaW_isunit(L, 1)) {
2221  lua_unit& u = *luaW_checkunit_ref(L, 1);
2222  if (u.on_map()) {
2223  loc = u->get_location();
2224  if (!map().on_board(loc)) {
2225  return luaL_argerror(L, 1, "invalid location");
2226  }
2227  } else if (int side = u.on_recall_list()) {
2228  team &t = board().get_team(side);
2229  // Should it use underlying ID instead?
2231  } else {
2232  return luaL_argerror(L, 1, "can't erase private units");
2233  }
2234  } else if (luaW_tolocation(L, 1, loc)) {
2235  if (!map().on_board(loc)) {
2236  return luaL_argerror(L, 1, "invalid location");
2237  }
2238  } else {
2239  return luaL_argerror(L, 1, "expected unit or location");
2240  }
2241 
2242  units().erase(loc);
2243  resources::whiteboard->on_kill_unit();
2244  return 0;
2245 }
2246 
2247 /**
2248  * Puts a unit on a recall list.
2249  * - Arg 1: WML table or unit.
2250  * - Arg 2: (optional) side.
2251  */
2253 {
2254  if(map_locked_) {
2255  return luaL_error(L, "Attempted to move a unit while the map is locked");
2256  }
2257  lua_unit *lu = nullptr;
2258  unit_ptr u = unit_ptr();
2259  int side = lua_tointeger(L, 2);
2260  if (static_cast<unsigned>(side) > teams().size()) side = 0;
2261 
2262  if(luaW_isunit(L, 1)) {
2263  lu = luaW_checkunit_ref(L, 1);
2264  u = lu->get_shared();
2265  if(lu->on_recall_list() && lu->on_recall_list() == side) {
2266  return luaL_argerror(L, 1, "unit already on recall list");
2267  }
2268  } else {
2269  const vconfig* vcfg = nullptr;
2270  config cfg = luaW_checkconfig(L, 1, vcfg);
2271  u = unit::create(cfg, true, vcfg);
2272  }
2273 
2274  if (!side) {
2275  side = u->side();
2276  } else {
2277  u->set_side(side);
2278  }
2279  team &t = board().get_team(side);
2280  // Avoid duplicates in the recall list.
2281  std::size_t uid = u->underlying_id();
2283  t.recall_list().add(u);
2284  if (lu) {
2285  if (lu->on_map()) {
2286  units().erase(u->get_location());
2287  resources::whiteboard->on_kill_unit();
2288  u->anim_comp().clear_haloes();
2289  }
2290  lu->lua_unit::~lua_unit();
2291  new(lu) lua_unit(side, uid);
2292  }
2293 
2294  return 0;
2295 }
2296 
2297 /**
2298  * Extracts a unit from the map or a recall list and gives it to Lua.
2299  * - Arg 1: unit userdata.
2300  */
2302 {
2303  if(map_locked_) {
2304  return luaL_error(L, "Attempted to remove a unit while the map is locked");
2305  }
2306  lua_unit* lu = luaW_checkunit_ref(L, 1);
2307  unit_ptr u = lu->get_shared();
2308 
2309  if (lu->on_map()) {
2310  u = units().extract(u->get_location());
2311  assert(u);
2312  u->anim_comp().clear_haloes();
2313  } else if (int side = lu->on_recall_list()) {
2314  team &t = board().get_team(side);
2315  unit_ptr v = u->clone();
2316  t.recall_list().erase_if_matches_id(u->id());
2317  u = v;
2318  } else {
2319  return 0;
2320  }
2321 
2322  lu->lua_unit::~lua_unit();
2323  new(lu) lua_unit(u);
2324  return 0;
2325 }
2326 
2327 /**
2328  * Finds a vacant tile.
2329  * - Arg 1: location.
2330  * - Arg 2: optional unit for checking movement type.
2331  * - Rets 1,2: location.
2332  */
2334 {
2335  map_location loc = luaW_checklocation(L, 1);
2336 
2337  unit_ptr u;
2338  if (!lua_isnoneornil(L, 2)) {
2339  if(luaW_isunit(L, 2)) {
2340  u = luaW_checkunit_ptr(L, 2, false);
2341  } else {
2342  const vconfig* vcfg = nullptr;
2343  config cfg = luaW_checkconfig(L, 2, vcfg);
2344  u = unit::create(cfg, false, vcfg);
2345  }
2346  }
2347 
2348  map_location res = find_vacant_tile(loc, pathfind::VACANT_ANY, u.get());
2349 
2350  if (!res.valid()) return 0;
2351  lua_pushinteger(L, res.wml_x());
2352  lua_pushinteger(L, res.wml_y());
2353  return 2;
2354 }
2355 
2356 /**
2357  * Floats some text on the map.
2358  * - Arg 1: location.
2359  * - Arg 2: string.
2360  * - Arg 3: color.
2361  */
2363 {
2364  map_location loc = luaW_checklocation(L, 1);
2365  color_t color = font::LABEL_COLOR;
2366 
2367  t_string text = luaW_checktstring(L, 2);
2368  if (!lua_isnoneornil(L, 3)) {
2370  }
2371 
2372  if (game_display_) {
2373  game_display_->float_label(loc, text, color);
2374  }
2375  return 0;
2376 }
2377 
2378 /**
2379  * Creates a unit from its WML description.
2380  * - Arg 1: WML table.
2381  * - Ret 1: unit userdata.
2382  */
2384 {
2385  const vconfig* vcfg = nullptr;
2386  config cfg = luaW_checkconfig(L, 1, vcfg);
2387  unit_ptr u = unit::create(cfg, true, vcfg);
2388  luaW_pushunit(L, u);
2389  return 1;
2390 }
2391 
2392 /**
2393  * Copies a unit.
2394  * - Arg 1: unit userdata.
2395  * - Ret 1: unit userdata.
2396  */
2398 {
2399  unit& u = luaW_checkunit(L, 1);
2400  luaW_pushunit(L, u.clone());
2401  return 1;
2402 }
2403 
2404 /**
2405  * Returns unit resistance against a given attack type.
2406  * - Arg 1: unit userdata.
2407  * - Arg 2: string containing the attack type.
2408  * - Arg 3: boolean indicating if attacker.
2409  * - Arg 4: optional location.
2410  * - Ret 1: integer.
2411  */
2413 {
2414  const unit& u = luaW_checkunit(L, 1);
2415  char const *m = luaL_checkstring(L, 2);
2416  bool a = false;
2417  map_location loc = u.get_location();
2418 
2419  if(lua_isboolean(L, 3)) {
2420  a = luaW_toboolean(L, 3);
2421  if(!lua_isnoneornil(L, 4)) {
2422  loc = luaW_checklocation(L, 4);
2423  }
2424  } else if(!lua_isnoneornil(L, 3)) {
2425  loc = luaW_checklocation(L, 3);
2426  }
2427 
2428  lua_pushinteger(L, 100 - u.resistance_against(m, a, loc));
2429  return 1;
2430 }
2431 
2432 /**
2433  * Returns unit movement cost on a given terrain.
2434  * - Arg 1: unit userdata.
2435  * - Arg 2: string containing the terrain type.
2436  * - Ret 1: integer.
2437  */
2439 {
2440  const unit& u = luaW_checkunit(L, 1);
2442  map_location loc;
2443  if(luaW_tolocation(L, 2, loc)) {
2444  t = resources::gameboard->map()[loc];
2445  } else if(lua_isstring(L, 2)) {
2446  char const *m = luaL_checkstring(L, 2);
2448  } else return luaW_type_error(L, 2, "location or terrain string");
2449  lua_pushinteger(L, u.movement_cost(t));
2450  return 1;
2451 }
2452 
2453 /**
2454  * Returns unit vision cost on a given terrain.
2455  * - Arg 1: unit userdata.
2456  * - Arg 2: string containing the terrain type.
2457  * - Ret 1: integer.
2458  */
2460 {
2461  const unit& u = luaW_checkunit(L, 1);
2463  map_location loc;
2464  if(luaW_tolocation(L, 2, loc)) {
2465  t = resources::gameboard->map()[loc];
2466  } else if(lua_isstring(L, 2)) {
2467  char const *m = luaL_checkstring(L, 2);
2469  } else return luaW_type_error(L, 2, "location or terrain string");
2470  lua_pushinteger(L, u.vision_cost(t));
2471  return 1;
2472 }
2473 
2474 /**
2475  * Returns unit jamming cost on a given terrain.
2476  * - Arg 1: unit userdata.
2477  * - Arg 2: string containing the terrain type.
2478  * - Ret 1: integer.
2479  */
2481 {
2482  const unit& u = luaW_checkunit(L, 1);
2484  map_location loc;
2485  if(luaW_tolocation(L, 2, loc)) {
2486  t = resources::gameboard->map()[loc];
2487  } else if(lua_isstring(L, 2)) {
2488  char const *m = luaL_checkstring(L, 2);
2490  } else return luaW_type_error(L, 2, "location or terrain string");
2491  lua_pushinteger(L, u.jamming_cost(t));
2492  return 1;
2493 }
2494 
2495 /**
2496  * Returns unit defense on a given terrain.
2497  * - Arg 1: unit userdata.
2498  * - Arg 2: string containing the terrain type.
2499  * - Ret 1: integer.
2500  */
2502 {
2503  const unit& u = luaW_checkunit(L, 1);
2505  map_location loc;
2506  if(luaW_tolocation(L, 2, loc)) {
2507  t = resources::gameboard->map()[loc];
2508  } else if(lua_isstring(L, 2)) {
2509  char const *m = luaL_checkstring(L, 2);
2511  } else return luaW_type_error(L, 2, "location or terrain string");
2512  lua_pushinteger(L, 100 - u.defense_modifier(t));
2513  return 1;
2514 }
2515 
2516 /**
2517  * Returns true if the unit has the given ability enabled.
2518  * - Arg 1: unit userdata.
2519  * - Arg 2: string.
2520  * - Ret 1: boolean.
2521  */
2523 {
2524  const unit& u = luaW_checkunit(L, 1);
2525  char const *m = luaL_checkstring(L, 2);
2527  return 1;
2528 }
2529 
2530 /**
2531  * Changes a unit to the given unit type.
2532  * - Arg 1: unit userdata.
2533  * - Arg 2: unit type name
2534  * - Arg 3: (optional) unit variation name
2535  */
2537 {
2538  unit& u = luaW_checkunit(L, 1);
2539  char const *m = luaL_checkstring(L, 2);
2540  const unit_type *utp = unit_types.find(m);
2541  if (!utp) return luaL_argerror(L, 2, "unknown unit type");
2542  if(lua_isstring(L, 3)) {
2543  const std::string& m2 = lua_tostring(L, 3);
2544  if(!utp->has_variation(m2)) return luaL_argerror(L, 2, "unknown unit variation");
2545  utp = &utp->get_variation(m2);
2546  }
2547  u.advance_to(*utp);
2548 
2549  return 0;
2550 }
2551 
2552 /**
2553  * Puts a table at the top of the stack with some combat result.
2554  */
2555 static void luaW_pushsimdata(lua_State *L, const combatant &cmb)
2556 {
2557  int n = cmb.hp_dist.size();
2558  lua_createtable(L, 0, 4);
2559  lua_pushnumber(L, cmb.poisoned);
2560  lua_setfield(L, -2, "poisoned");
2561  lua_pushnumber(L, cmb.slowed);
2562  lua_setfield(L, -2, "slowed");
2563  lua_pushnumber(L, cmb.untouched);
2564  lua_setfield(L, -2, "untouched");
2565  lua_pushnumber(L, cmb.average_hp());
2566  lua_setfield(L, -2, "average_hp");
2567  lua_createtable(L, n, 0);
2568  for (int i = 0; i < n; ++i) {
2569  lua_pushnumber(L, cmb.hp_dist[i]);
2570  lua_rawseti(L, -2, i);
2571  }
2572  lua_setfield(L, -2, "hp_chance");
2573 }
2574 
2575 /**
2576  * Puts a table at the top of the stack with information about the combatants' weapons.
2577  */
2579 {
2580 
2581  lua_createtable(L, 0, 16);
2582 
2583  lua_pushnumber(L, bcustats.num_blows);
2584  lua_setfield(L, -2, "num_blows");
2585  lua_pushnumber(L, bcustats.damage);
2586  lua_setfield(L, -2, "damage");
2587  lua_pushnumber(L, bcustats.chance_to_hit);
2588  lua_setfield(L, -2, "chance_to_hit");
2589  lua_pushboolean(L, bcustats.poisons);
2590  lua_setfield(L, -2, "poisons");
2591  lua_pushboolean(L, bcustats.slows);
2592  lua_setfield(L, -2, "slows");
2593  lua_pushboolean(L, bcustats.petrifies);
2594  lua_setfield(L, -2, "petrifies");
2595  lua_pushboolean(L, bcustats.plagues);
2596  lua_setfield(L, -2, "plagues");
2597  lua_pushstring(L, bcustats.plague_type.c_str());
2598  lua_setfield(L, -2, "plague_type");
2599  lua_pushboolean(L, bcustats.backstab_pos);
2600  lua_setfield(L, -2, "backstabs");
2601  lua_pushnumber(L, bcustats.rounds);
2602  lua_setfield(L, -2, "rounds");
2603  lua_pushboolean(L, bcustats.firststrike);
2604  lua_setfield(L, -2, "firststrike");
2605  lua_pushboolean(L, bcustats.drains);
2606  lua_setfield(L, -2, "drains");
2607  lua_pushnumber(L, bcustats.drain_constant);
2608  lua_setfield(L, -2, "drain_constant");
2609  lua_pushnumber(L, bcustats.drain_percent);
2610  lua_setfield(L, -2, "drain_percent");
2611 
2612 
2613  //if we called simulate_combat without giving an explicit weapon this can be useful.
2614  lua_pushnumber(L, bcustats.attack_num);
2615  lua_setfield(L, -2, "attack_num"); // DEPRECATED
2616  lua_pushnumber(L, bcustats.attack_num + 1);
2617  lua_setfield(L, -2, "number");
2618  //this is nullptr when there is no counter weapon
2619  if(bcustats.weapon != nullptr)
2620  {
2621  lua_pushstring(L, bcustats.weapon->id().c_str());
2622  lua_setfield(L, -2, "name");
2623  luaW_pushweapon(L, bcustats.weapon);
2624  lua_setfield(L, -2, "weapon");
2625  }
2626 
2627 }
2628 
2629 /**
2630  * Simulates a combat between two units.
2631  * - Arg 1: attacker userdata.
2632  * - Arg 2: optional weapon index.
2633  * - Arg 3: defender userdata.
2634  * - Arg 4: optional weapon index.
2635  *
2636  * - Ret 1: attacker results.
2637  * - Ret 2: defender results.
2638  * - Ret 3: info about the attacker weapon.
2639  * - Ret 4: info about the defender weapon.
2640  */
2642 {
2643  int arg_num = 1, att_w = -1, def_w = -1;
2644 
2645  unit_const_ptr att = luaW_checkunit(L, arg_num).shared_from_this();
2646  ++arg_num;
2647  if (lua_isnumber(L, arg_num)) {
2648  att_w = lua_tointeger(L, arg_num) - 1;
2649  if (att_w < 0 || att_w >= static_cast<int>(att->attacks().size()))
2650  return luaL_argerror(L, arg_num, "weapon index out of bounds");
2651  ++arg_num;
2652  }
2653 
2654  unit_const_ptr def = luaW_checkunit(L, arg_num).shared_from_this();
2655  ++arg_num;
2656  if (lua_isnumber(L, arg_num)) {
2657  def_w = lua_tointeger(L, arg_num) - 1;
2658  if (def_w < 0 || def_w >= static_cast<int>(def->attacks().size()))
2659  return luaL_argerror(L, arg_num, "weapon index out of bounds");
2660  ++arg_num;
2661  }
2662 
2663  battle_context context(units(), att->get_location(),
2664  def->get_location(), att_w, def_w, 0.0, nullptr, att, def);
2665 
2666  luaW_pushsimdata(L, context.get_attacker_combatant());
2667  luaW_pushsimdata(L, context.get_defender_combatant());
2668  luaW_pushsimweapon(L, context.get_attacker_stats());
2669  luaW_pushsimweapon(L, context.get_defender_stats());
2670  return 4;
2671 }
2672 
2673 /**
2674  * Modifies the music playlist.
2675  * - Arg 1: WML table, or nil to force changes.
2676  */
2678 {
2679  deprecated_message("wesnoth.set_music", DEP_LEVEL::INDEFINITE, "", "Use the wesnoth.playlist table instead!");
2680  if (lua_isnoneornil(L, 1)) {
2682  return 0;
2683  }
2684 
2685  config cfg = luaW_checkconfig(L, 1);
2687  return 0;
2688 }
2689 
2690 /**
2691  * Plays a sound, possibly repeated.
2692  * - Arg 1: string.
2693  * - Arg 2: optional integer.
2694  */
2696 {
2697  char const *m = luaL_checkstring(L, 1);
2698  if (play_controller_.is_skipping_replay()) return 0;
2699  int repeats = lua_tointeger(L, 2);
2700  sound::play_sound(m, sound::SOUND_FX, repeats);
2701  return 0;
2702 }
2703 
2704 /**
2705  * Gets/sets the current sound volume
2706  * - Arg 1: (optional) New volume to set
2707  * - Return: Original volume
2708  */
2710 {
2711  int vol = preferences::sound_volume();
2712  lua_pushnumber(L, sound::get_sound_volume() * 100.0 / vol);
2713  if(lua_isnumber(L, 1)) {
2714  float rel = lua_tonumber(L, 1);
2715  if(rel < 0.0f || rel > 100.0f) {
2716  return luaL_argerror(L, 1, "volume must be in range 0..100");
2717  }
2718  vol = static_cast<int>(rel*vol / 100.0f);
2720  }
2721  return 1;
2722 }
2723 
2724 /**
2725  * Scrolls to given tile.
2726  * - Arg 1: location.
2727  * - Arg 2: boolean preventing scroll to fog.
2728  * - Arg 3: boolean specifying whether to warp instantly.
2729  * - Arg 4: boolean specifying whether to skip if already onscreen
2730  */
2732 {
2733  map_location loc = luaW_checklocation(L, 1);
2734  bool check_fogged = luaW_toboolean(L, 2);
2736  ? luaW_toboolean(L, 3)
2739  : luaW_toboolean(L, 3)
2742  ;
2743  if (game_display_) {
2744  game_display_->scroll_to_tile(loc, scroll, check_fogged);
2745  }
2746  return 0;
2747 }
2748 
2750 {
2751  events::command_disabler command_disabler;
2752  deprecated_message("wesnoth.select_hex", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use wesnoth.units.select and/or wesnoth.interface.highlight_hex instead.");
2753 
2754  // Need this because check_location may change the stack
2755  // By doing this now, we ensure that it won't do so when
2756  // intf_select_unit and intf_highlight_hex call it.
2757  const map_location loc = luaW_checklocation(L, 1);
2758  luaW_pushlocation(L, loc);
2759  lua_replace(L, 1);
2760 
2761  intf_select_unit(L);
2762  if(!lua_isnoneornil(L, 2) && luaW_toboolean(L,2)) {
2763  intf_highlight_hex(L);
2764  }
2765  return 0;
2766 }
2767 
2768 /**
2769  * Selects and highlights the given location on the map.
2770  * - Arg 1: location.
2771  * - Args 2,3: booleans
2772  */
2774 {
2775  events::command_disabler command_disabler;
2776  if(lua_isnoneornil(L, 1)) {
2777  play_controller_.get_mouse_handler_base().select_hex(map_location::null_location(), false, false, false);
2778  return 0;
2779  }
2780  const map_location loc = luaW_checklocation(L, 1);
2781  if(!map().on_board(loc)) return luaL_argerror(L, 1, "not on board");
2782  bool highlight = true;
2783  if(!lua_isnoneornil(L, 2))
2784  highlight = luaW_toboolean(L, 2);
2785  const bool fire_event = luaW_toboolean(L, 3);
2786  play_controller_.get_mouse_handler_base().select_hex(
2787  loc, false, highlight, fire_event);
2788  return 0;
2789 }
2790 
2791 /**
2792  * Deselects any highlighted hex on the map.
2793  * No arguments or return values
2794  */
2796 {
2797  if(game_display_) {
2798  game_display_->highlight_hex(map_location::null_location());
2799  }
2800 
2801  return 0;
2802 }
2803 
2804 /**
2805  * Return true if a replay is in progress but the player has chosen to skip it
2806  */
2808 {
2809  bool skipping = play_controller_.is_skipping_replay() || play_controller_.is_skipping_story();
2810  if (!skipping) {
2811  skipping = game_state_.events_manager_->pump().context_skip_messages();
2812  }
2813  lua_pushboolean(L, skipping);
2814  return 1;
2815 }
2816 
2817 /**
2818  * Set whether to skip messages
2819  * Arg 1 (optional) - boolean
2820  */
2822 {
2823  bool skip = true;
2824  if (!lua_isnone(L, 1)) {
2825  skip = luaW_toboolean(L, 1);
2826  }
2827  game_state_.events_manager_->pump().context_skip_messages(skip);
2828  return 0;
2829 }
2830 
2831 namespace
2832 {
2833  struct lua_synchronize : mp_sync::user_choice
2834  {
2835  lua_State *L;
2836  int user_choice_index;
2837  int random_choice_index;
2838  int ai_choice_index;
2839  std::string desc;
2840  lua_synchronize(lua_State *l, const std::string& descr, int user_index, int random_index = 0, int ai_index = 0)
2841  : L(l)
2842  , user_choice_index(user_index)
2843  , random_choice_index(random_index)
2844  , ai_choice_index(ai_index != 0 ? ai_index : user_index)
2845  , desc(descr)
2846  {}
2847 
2848  virtual config query_user(int side) const override
2849  {
2850  bool is_local_ai = lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).board().get_team(side).is_local_ai();
2851  config cfg;
2852  query_lua(side, is_local_ai ? ai_choice_index : user_choice_index, cfg);
2853  return cfg;
2854  }
2855 
2856  virtual config random_choice(int side) const override
2857  {
2858  config cfg;
2859  if(random_choice_index != 0 && lua_isfunction(L, random_choice_index)) {
2860  query_lua(side, random_choice_index, cfg);
2861  }
2862  return cfg;
2863  }
2864 
2865  virtual std::string description() const override
2866  {
2867  return desc;
2868  }
2869 
2870  void query_lua(int side, int function_index, config& cfg) const
2871  {
2872  assert(cfg.empty());
2873  lua_pushvalue(L, function_index);
2874  lua_pushnumber(L, side);
2875  if (luaW_pcall(L, 1, 1, false)) {
2876  if(!luaW_toconfig(L, -1, cfg)) {
2877  lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).log_error("function returned to wesnoth.synchronize_choice a table which was partially invalid");
2878  }
2879  }
2880  }
2881  //Although lua's sync_choice can show a dialog, (and will in most cases)
2882  //we return false to enable other possible things that do not contain UI things.
2883  //it's in the responsibility of the umc dev to not show dialogs during prestart events.
2884  virtual bool is_visible() const override { return false; }
2885  };
2886 }//unnamed namespace for lua_synchronize
2887 
2888 /**
2889  * Ensures a value is synchronized among all the clients.
2890  * - Arg 1: optional string specifying the type id of the choice.
2891  * - Arg 2: function to compute the value, called if the client is the master.
2892  * - Arg 3: optional function, called instead of the first function if the user is not human.
2893  * - Arg 4: optional integer specifying, on which side the function should be evaluated.
2894  * - Ret 1: WML table returned by the function.
2895  */
2897 {
2898  std::string tagname = "input";
2899  t_string desc = _("input");
2900  int human_func = 0;
2901  int ai_func = 0;
2902  int side_for;
2903 
2904  int nextarg = 1;
2905  if(!lua_isfunction(L, nextarg) && luaW_totstring(L, nextarg, desc) ) {
2906  ++nextarg;
2907  }
2908  if(lua_isfunction(L, nextarg)) {
2909  human_func = nextarg++;
2910  }
2911  else {
2912  return luaL_argerror(L, nextarg, "expected a function");
2913  }
2914  if(lua_isfunction(L, nextarg)) {
2915  ai_func = nextarg++;
2916  }
2917  side_for = lua_tointeger(L, nextarg);
2918 
2919  config cfg = mp_sync::get_user_choice(tagname, lua_synchronize(L, desc, human_func, 0, ai_func), side_for);
2920  luaW_pushconfig(L, cfg);
2921  return 1;
2922 }
2923 /**
2924  * Ensures a value is synchronized among all the clients.
2925  * - Arg 1: optional string the id of this type of user input, may only contain characters a-z and '_'
2926  * - Arg 2: function to compute the value, called if the client is the master.
2927  * - Arg 3: an optional function to compute the value, if the side was null/empty controlled.
2928  * - Arg 4: an array of integers specifying, on which side the function should be evaluated.
2929  * - Ret 1: a map int -> WML tabls.
2930  */
2932 {
2933  std::string tagname = "input";
2934  t_string desc = _("input");
2935  int human_func = 0;
2936  int null_func = 0;
2937  std::vector<int> sides_for;
2938 
2939  int nextarg = 1;
2940  if(!lua_isfunction(L, nextarg) && luaW_totstring(L, nextarg, desc) ) {
2941  ++nextarg;
2942  }
2943  if(lua_isfunction(L, nextarg)) {
2944  human_func = nextarg++;
2945  }
2946  else {
2947  return luaL_argerror(L, nextarg, "expected a function");
2948  }
2949  if(lua_isfunction(L, nextarg)) {
2950  null_func = nextarg++;
2951  };
2952  sides_for = lua_check<std::vector<int>>(L, nextarg++);
2953 
2954  lua_push(L, mp_sync::get_user_choice_multiple_sides(tagname, lua_synchronize(L, desc, human_func, null_func), std::set<int>(sides_for.begin(), sides_for.end())));
2955  return 1;
2956 }
2957 
2958 
2959 /**
2960  * Calls a function in an unsynced context (this specially means that all random calls used by that function will be unsynced).
2961  * This is usually used together with an unsynced if like 'if controller != network'
2962  * - Arg 1: function that will be called during the unsynced context.
2963  */
2965 {
2966  set_scontext_unsynced sync;
2967  lua_pushvalue(L, 1);
2968  luaW_pcall(L, 0, 0, false);
2969  return 0;
2970 }
2971 
2972 /**
2973  * Gets all the locations matching a given filter.
2974  * - Arg 1: WML table.
2975  * - Arg 2: Optional reference unit (teleport_unit)
2976  * - Ret 1: array of integer pairs.
2977  */
2979 {
2980  vconfig filter = luaW_checkvconfig(L, 1);
2981 
2982  std::set<map_location> res;
2983  filter_context & fc = game_state_;
2984  const terrain_filter t_filter(filter, &fc);
2985  if(luaW_isunit(L, 2)) {
2986  t_filter.get_locations(res, *luaW_tounit(L, 2), true);
2987  } else {
2988  t_filter.get_locations(res, true);
2989  }
2990 
2991  lua_createtable(L, res.size(), 0);
2992  int i = 1;
2993  for (const map_location& loc : res)
2994  {
2995  lua_createtable(L, 2, 0);
2996  lua_pushinteger(L, loc.wml_x());
2997  lua_rawseti(L, -2, 1);
2998  lua_pushinteger(L, loc.wml_y());
2999  lua_rawseti(L, -2, 2);
3000  lua_rawseti(L, -2, i);
3001  ++i;
3002  }
3003  return 1;
3004 }
3005 
3006 /**
3007  * Gets all the villages matching a given filter, or all the villages on the map if no filter is given.
3008  * - Arg 1: WML table (optional).
3009  * - Ret 1: array of integer pairs.
3010  */
3012 {
3013  std::vector<map_location> locs = map().villages();
3014  lua_newtable(L);
3015  int i = 1;
3016 
3017  vconfig filter = luaW_checkvconfig(L, 1);
3018 
3019  filter_context & fc = game_state_;
3020  for(std::vector<map_location>::const_iterator it = locs.begin(); it != locs.end(); ++it) {
3021  bool matches = terrain_filter(filter, &fc).match(*it);
3022  if (matches) {
3023  lua_createtable(L, 2, 0);
3024  lua_pushinteger(L, it->wml_x());
3025  lua_rawseti(L, -2, 1);
3026  lua_pushinteger(L, it->wml_y());
3027  lua_rawseti(L, -2, 2);
3028  lua_rawseti(L, -2, i);
3029  ++i;
3030  }
3031  }
3032  return 1;
3033 }
3034 
3035 /**
3036  * Matches a location against the given filter.
3037  * - Arg 1: location.
3038  * - Arg 2: WML table.
3039  * - Arg 3: Optional reference unit (teleport_unit)
3040  * - Ret 1: boolean.
3041  */
3043 {
3044  map_location loc = luaW_checklocation(L, 1);
3045  vconfig filter = luaW_checkvconfig(L, 2, true);
3046 
3047  if (filter.null()) {
3048  lua_pushboolean(L, true);
3049  return 1;
3050  }
3051 
3052  filter_context & fc = game_state_;
3053  const terrain_filter t_filter(filter, &fc);
3054  if(luaW_isunit(L, 3)) {
3055  lua_pushboolean(L, t_filter.match(loc, *luaW_tounit(L, 3)));
3056  } else {
3057  lua_pushboolean(L, t_filter.match(loc));
3058  }
3059  return 1;
3060 }
3061 
3062 
3063 
3064 /**
3065  * Matches a side against the given filter.
3066  * - Args 1: side number.
3067  * - Arg 2: WML table.
3068  * - Ret 1: boolean.
3069  */
3071 {
3072  vconfig filter = luaW_checkvconfig(L, 2, true);
3073 
3074  if (filter.null()) {
3075  lua_pushboolean(L, true);
3076  return 1;
3077  }
3078 
3079  filter_context & fc = game_state_;
3080  side_filter s_filter(filter, &fc);
3081 
3082  if(team* t = luaW_toteam(L, 1)) {
3083  lua_pushboolean(L, s_filter.match(*t));
3084  } else {
3085  unsigned side = luaL_checkinteger(L, 1) - 1;
3086  if (side >= teams().size()) return 0;
3087  lua_pushboolean(L, s_filter.match(side + 1));
3088  }
3089  return 1;
3090 }
3091 
3093 {
3094  int team_i;
3095  if(team* t = luaW_toteam(L, 1)) {
3096  team_i = t->side();
3097  } else {
3098  team_i = luaL_checkinteger(L, 1);
3099  }
3100  std::string flag = luaL_optlstring(L, 2, "", nullptr);
3101  std::string color = luaL_optlstring(L, 3, "", nullptr);
3102 
3103  if(flag.empty() && color.empty()) {
3104  return 0;
3105  }
3106  if(team_i < 1 || static_cast<std::size_t>(team_i) > teams().size()) {
3107  return luaL_error(L, "set_side_id: side number %d out of range", team_i);
3108  }
3109  team& side = board().get_team(team_i);
3110 
3111  if(!color.empty()) {
3112  side.set_color(color);
3113  }
3114  if(!flag.empty()) {
3115  side.set_flag(flag);
3116  }
3117 
3118  game_display_->reinit_flags_for_team(side);
3119  return 0;
3120 }
3121 
3122 static int intf_modify_ai(lua_State *L, const char* action)
3123 {
3124  int side_num;
3125  if(team* t = luaW_toteam(L, 1)) {
3126  side_num = t->side();
3127  } else {
3128  side_num = luaL_checkinteger(L, 1);
3129  }
3131  config cfg {
3132  "action", action,
3133  "path", path
3134  };
3135  if(strcmp(action, "delete") == 0) {
3137  return 0;
3138  }
3139  config component = luaW_checkconfig(L, 3);
3140  std::size_t len = std::string::npos, open_brak = path.find_last_of('[');
3141  std::size_t dot = path.find_last_of('.');
3142  if(open_brak != len) {
3143  len = open_brak - dot - 1;
3144  }
3145  cfg.add_child(path.substr(dot + 1, len), component);
3147  return 0;
3148 }
3149 
3151 {
3152  int side_num;
3153  if(team* t = luaW_toteam(L, 1)) {
3154  side_num = t->side();
3155  } else {
3156  side_num = luaL_checkinteger(L, 1);
3157  }
3158  if(lua_isstring(L, 2)) {
3159  std::string file = luaL_checkstring(L, 2);
3160  if(!ai::manager::get_singleton().add_ai_for_side_from_file(side_num, file)) {
3161  std::string err = formatter() << "Could not load AI for side " << side_num << " from file " << file;
3162  lua_pushlstring(L, err.c_str(), err.length());
3163  return lua_error(L);
3164  }
3165  } else {
3167  }
3168  return 0;
3169 }
3170 
3172 {
3173  int side_num;
3174  if(team* t = luaW_toteam(L, 1)) {
3175  side_num = t->side();
3176  } else {
3177  side_num = luaL_checkinteger(L, 1);
3178  }
3179  config cfg = luaW_checkconfig(L, 2);
3180  if(!cfg.has_child("ai")) {
3181  cfg = config {"ai", cfg};
3182  }
3183  bool added_dummy_stage = false;
3184  if(!cfg.child("ai").has_child("stage")) {
3185  added_dummy_stage = true;
3186  cfg.child("ai").add_child("stage", config {"name", "empty"});
3187  }
3189  if(added_dummy_stage) {
3190  for(auto iter = cfg.ordered_begin(); iter != cfg.ordered_end(); iter++) {
3191  if(iter->key == "stage" && iter->cfg["name"] == "empty") {
3192  iter = cfg.erase(iter);
3193  }
3194  }
3195  }
3197  return 0;
3198 }
3199 
3201 {
3202  unsigned i = luaL_checkinteger(L, 1);
3203  if(i < 1 || i > teams().size()) return 0;
3204  luaW_pushteam(L, board().get_team(i));
3205  return 1;
3206 }
3207 
3208 /**
3209  * Returns a proxy table array for all sides matching the given SSF.
3210  * - Arg 1: SSF
3211  * - Ret 1: proxy table array
3212  */
3214 {
3215  LOG_LUA << "intf_get_sides called: this = " << std::hex << this << std::dec << " myname = " << my_name() << std::endl;
3216  std::vector<int> sides;
3217  const vconfig ssf = luaW_checkvconfig(L, 1, true);
3218  if(ssf.null()) {
3219  for (unsigned side_number = 1; side_number <= teams().size(); ++side_number) {
3220  sides.push_back(side_number);
3221  }
3222  } else {
3223  filter_context & fc = game_state_;
3224 
3225  side_filter filter(ssf, &fc);
3226  sides = filter.get_teams();
3227  }
3228 
3229  lua_settop(L, 0);
3230  lua_createtable(L, sides.size(), 0);
3231  unsigned index = 1;
3232  for(int side : sides) {
3233  luaW_pushteam(L, board().get_team(side));
3234  lua_rawseti(L, -2, index);
3235  ++index;
3236  }
3237 
3238  return 1;
3239 }
3240 
3241 /**
3242  * .Returns information about the global traits known to the engine.
3243  * - Ret 1: Table with named fields holding wml tables describing the traits.
3244  */
3246 {
3247  lua_newtable(L);
3248  for(const config& trait : unit_types.traits()) {
3249  const std::string& id = trait["id"];
3250  //It seems the engine does nowhere check the id field for emptyness or duplicates
3251  //(also not later on).
3252  //However, the worst thing to happen is that the trait read later overwrites the older one,
3253  //and this is not the right place for such checks.
3254  lua_pushstring(L, id.c_str());
3255  luaW_pushconfig(L, trait);
3256  lua_rawset(L, -3);
3257  }
3258  return 1;
3259 }
3260 
3261 /**
3262  * Adds a modification to a unit.
3263  * - Arg 1: unit.
3264  * - Arg 2: string.
3265  * - Arg 3: WML table.
3266  * - Arg 4: (optional) Whether to add to [modifications] - default true
3267  */
3269 {
3270  unit& u = luaW_checkunit(L, 1);
3271  char const *m = luaL_checkstring(L, 2);
3272  std::string sm = m;
3273  if (sm == "advance") { // Maintain backwards compatibility
3274  sm = "advancement";
3275  deprecated_message("\"advance\" modification type", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use \"advancement\" instead.");
3276  }
3277  if (sm != "advancement" && sm != "object" && sm != "trait") {
3278  return luaL_argerror(L, 2, "unknown modification type");
3279  }
3280  bool write_to_mods = true;
3281  if (!lua_isnone(L, 4)) {
3282  write_to_mods = luaW_toboolean(L, 4);
3283  }
3284  if(sm.empty()) {
3285  write_to_mods = false;
3286  }
3287 
3288  config cfg = luaW_checkconfig(L, 3);
3289  u.add_modification(sm, cfg, !write_to_mods);
3290  return 0;
3291 }
3292 
3293 /**
3294  * Removes modifications from a unit
3295  * - Arg 1: unit
3296  * - Arg 2: table (filter as [filter_wml])
3297  * - Arg 3: type of modification (default "object")
3298  */
3300 {
3301  unit& u = luaW_checkunit(L, 1);
3302  config filter = luaW_checkconfig(L, 2);
3303  std::string tag = luaL_optstring(L, 3, "object");
3304  //TODO
3305  if(filter.attribute_count() == 1 && filter.all_children_count() == 0 && filter.attribute_range().front().first == "duration") {
3306  u.expire_modifications(filter["duration"]);
3307  } else {
3308  for(config& obj : u.get_modifications().child_range(tag)) {
3309  if(obj.matches(filter)) {
3310  obj["duration"] = "now";
3311  }
3312  }
3313  u.expire_modifications("now");
3314  }
3315  return 0;
3316 }
3317 
3318 /**
3319  * Advances a unit if the unit has enough xp.
3320  * - Arg 1: unit.
3321  * - Arg 2: optional boolean whether to animate the advancement.
3322  * - Arg 3: optional boolean whether to fire advancement events.
3323  */
3325 {
3326  events::command_disabler command_disabler;
3327  unit& u = luaW_checkunit(L, 1, true);
3329  if(lua_isboolean(L, 2)) {
3330  par.animate(luaW_toboolean(L, 2));
3331  }
3332  if(lua_isboolean(L, 3)) {
3333  par.fire_events(luaW_toboolean(L, 3));
3334  }
3335  advance_unit_at(par);
3336  return 0;
3337 }
3338 
3339 
3340 /**
3341  * Adds a new known unit type to the help system.
3342  * - Arg 1: string.
3343  */
3345 {
3346  char const *ty = luaL_checkstring(L, 1);
3347  if(!unit_types.find(ty))
3348  {
3349  std::stringstream ss;
3350  ss << "unknown unit type: '" << ty << "'";
3351  return luaL_argerror(L, 1, ss.str().c_str());
3352  }
3353  preferences::encountered_units().insert(ty);
3354  return 0;
3355 }
3356 
3357 /**
3358  * Adds an overlay on a tile.
3359  * - Arg 1: location.
3360  * - Arg 2: WML table.
3361  */
3363 {
3364  map_location loc = luaW_checklocation(L, 1);
3365  vconfig cfg = luaW_checkvconfig(L, 2);
3366  const vconfig &ssf = cfg.child("filter_team");
3367 
3368  std::string team_name;
3369  if (!ssf.null()) {
3370  const std::vector<int>& teams = side_filter(ssf, &game_state_).get_teams();
3371  std::vector<std::string> team_names;
3372  std::transform(teams.begin(), teams.end(), std::back_inserter(team_names),
3373  [&](int team) { return game_state_.get_disp_context().get_team(team).team_name(); });
3374  team_name = utils::join(team_names);
3375  } else {
3376  team_name = cfg["team_name"].str();
3377  }
3378 
3379  if (game_display_) {
3380  game_display_->add_overlay(loc, cfg["image"], cfg["halo"],
3381  team_name, cfg["name"], cfg["visible_in_fog"].to_bool(true), cfg["z_order"].to_double(0));
3382  }
3383  return 0;
3384 }
3385 
3386 /**
3387  * Removes an overlay from a tile.
3388  * - Arg 1: location.
3389  * - Arg 2: optional string.
3390  */
3392 {
3393  map_location loc = luaW_checklocation(L, 1);
3394  char const *m = lua_tostring(L, 2);
3395 
3396  if (m) {
3397  if (game_display_) {
3398  game_display_->remove_single_overlay(loc, m);
3399  }
3400  } else {
3401  if (game_display_) {
3402  game_display_->remove_overlay(loc);
3403  }
3404  }
3405  return 0;
3406 }
3407 
3409 {
3410  replay& recorder = play_controller_.get_replay();
3411  const int nargs = lua_gettop(L);
3412  if(nargs < 2 || nargs > 3) {
3413  return luaL_error(L, "Wrong number of arguments to ai.log_replay() - should be 2 or 3 arguments.");
3414  }
3415  const std::string key = nargs == 2 ? luaL_checkstring(L, 1) : luaL_checkstring(L, 2);
3416  config cfg;
3417  if(nargs == 2) {
3418  recorder.add_log_data(key, luaL_checkstring(L, 2));
3419  } else if(luaW_toconfig(L, 3, cfg)) {
3420  recorder.add_log_data(luaL_checkstring(L, 1), key, cfg);
3421  } else if(!lua_isstring(L, 3)) {
3422  return luaL_argerror(L, 3, "accepts only string or config");
3423  } else {
3424  recorder.add_log_data(luaL_checkstring(L, 1), key, luaL_checkstring(L, 3));
3425  }
3426  return 0;
3427 }
3428 
3429 /// Adding new events
3431 {
3432  vconfig cfg(luaW_checkvconfig(L, 1));
3433  game_events::manager & man = *game_state_.events_manager_;
3434 
3435  if (!cfg["delayed_variable_substitution"].to_bool(true)) {
3437  } else {
3438  man.add_event_handler(cfg.get_config());
3439  }
3440  return 0;
3441 }
3442 
3444 {
3445  game_state_.events_manager_->remove_event_handler(luaL_checkstring(L, 1));
3446  return 0;
3447 }
3448 
3450 {
3451  if (game_display_) {
3452  vconfig cfg(luaW_checkvconfig(L, 1));
3453 
3454  game_display_->adjust_color_overlay(cfg["red"], cfg["green"], cfg["blue"]);
3455  game_display_->invalidate_all();
3456  game_display_->draw(true,true);
3457  }
3458  return 0;
3459 }
3460 
3461 /**
3462  * Delays engine for a while.
3463  * - Arg 1: integer.
3464  * - Arg 2: boolean (optional).
3465  */
3467 {
3468  if(gamedata().phase() == game_data::PRELOAD || gamedata().phase() == game_data::PRESTART || gamedata().phase() == game_data::INITIAL) {
3469  //don't call play_slice if the game ui is not active yet.
3470  return 0;
3471  }
3472  events::command_disabler command_disabler;
3473  lua_Integer delay = luaL_checkinteger(L, 1);
3474  if(delay == 0) {
3475  play_controller_.play_slice(false);
3476  return 0;
3477  }
3478  if(luaW_toboolean(L, 2) && game_display_ && game_display_->turbo_speed() > 0) {
3479  delay /= game_display_->turbo_speed();
3480  }
3481  const unsigned final = SDL_GetTicks() + delay;
3482  do {
3483  play_controller_.play_slice(false);
3484  CVideo::delay(10);
3485  } while (static_cast<int>(final - SDL_GetTicks()) > 0);
3486  return 0;
3487 }
3488 
3490 {
3491  if (game_display_) {
3492  vconfig cfg(luaW_checkvconfig(L, 1));
3493 
3494  game_display &screen = *game_display_;
3495 
3496  terrain_label label(screen.labels(), cfg.get_config());
3497 
3498  screen.labels().set_label(label.location(), label.text(), label.creator(), label.team_name(), label.color(),
3499  label.visible_in_fog(), label.visible_in_shroud(), label.immutable(), label.category(), label.tooltip());
3500  }
3501  return 0;
3502 }
3503 
3505 {
3506  if (game_display_) {
3507  game_display & screen = *game_display_;
3508 
3509  vconfig cfg(luaW_checkvconfig(L, 1));
3510  bool clear_shroud(luaW_toboolean(L, 2));
3511 
3512  // We do this twice so any applicable redraws happen both before and after
3513  // any events caused by redrawing shroud are fired
3514  bool result = screen.maybe_rebuild();
3515  if (!result) {
3516  screen.invalidate_all();
3517  }
3518 
3519  if (clear_shroud) {
3520  side_filter filter(cfg, &game_state_);
3521  for (const int side : filter.get_teams()){
3522  actions::clear_shroud(side);
3523  }
3524  screen.recalculate_minimap();
3525  }
3526 
3527  result = screen.maybe_rebuild();
3528  if (!result) {
3529  screen.invalidate_all();
3530  }
3531 
3532  screen.draw(true,true);
3533  }
3534  return 0;
3535 }
3536 
3537 /**
3538  * Lua frontend to the modify_ai functionality
3539  * - Arg 1: config.
3540  */
3542 {
3543  config cfg;
3544  luaW_toconfig(L, 1, cfg);
3545  int side = cfg["side"];
3546  deprecated_message("wesnoth.modify_ai", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use wesnoth.sides.add_ai_component, wesnoth.sides.delete_ai_component, or wesnoth.sides.change_ai_component.");
3548  return 0;
3549 }
3550 
3552 {
3553  bool exec = luaW_toboolean(L, -1);
3554  lua_pop(L, 1);
3555 
3556  lua_getfield(L, -1, "ca_ptr");
3557 
3558  ai::candidate_action *ca = static_cast<ai::candidate_action*>(lua_touserdata(L, -1));
3559  lua_pop(L, 2);
3560  if (exec) {
3561  ca->execute();
3562  return 0;
3563  }
3564  lua_pushinteger(L, ca->evaluate());
3565  return 1;
3566 }
3567 
3569 {
3570  lua_getfield(L, -1, "stg_ptr");
3571  ai::stage *stg = static_cast<ai::stage*>(lua_touserdata(L, -1));
3572  lua_pop(L, 2);
3573  stg->play_stage();
3574  return 0;
3575 }
3576 
3577 static void push_component(lua_State *L, ai::component* c, const std::string &ct = "")
3578 {
3579  lua_createtable(L, 0, 0); // Table for a component
3580 
3581  lua_pushstring(L, "name");
3582  lua_pushstring(L, c->get_name().c_str());
3583  lua_rawset(L, -3);
3584 
3585  lua_pushstring(L, "engine");
3586  lua_pushstring(L, c->get_engine().c_str());
3587  lua_rawset(L, -3);
3588 
3589  lua_pushstring(L, "id");
3590  lua_pushstring(L, c->get_id().c_str());
3591  lua_rawset(L, -3);
3592 
3593  if (ct == "candidate_action") {
3594  lua_pushstring(L, "ca_ptr");
3595  lua_pushlightuserdata(L, c);
3596  lua_rawset(L, -3);
3597 
3598  lua_pushstring(L, "exec");
3600  lua_rawset(L, -3);
3601  }
3602 
3603  if (ct == "stage") {
3604  lua_pushstring(L, "stg_ptr");
3605  lua_pushlightuserdata(L, c);
3606  lua_rawset(L, -3);
3607 
3608  lua_pushstring(L, "exec");
3610  lua_rawset(L, -3);
3611  }
3612 
3613 
3614  std::vector<std::string> c_types = c->get_children_types();
3615 
3616  for (std::vector<std::string>::const_iterator t = c_types.begin(); t != c_types.end(); ++t)
3617  {
3618  std::vector<ai::component*> children = c->get_children(*t);
3619  std::string type = *t;
3620  if (type == "aspect" || type == "goal" || type == "engine")
3621  {
3622  continue;
3623  }
3624 
3625  lua_pushstring(L, type.c_str());
3626  lua_createtable(L, 0, 0); // this table will be on top of the stack during recursive calls
3627 
3628  for (std::vector<ai::component*>::const_iterator i = children.begin(); i != children.end(); ++i)
3629  {
3630  lua_pushstring(L, (*i)->get_name().c_str());
3631  push_component(L, *i, type);
3632  lua_rawset(L, -3);
3633 
3634  //if (type == "candidate_action")
3635  //{
3636  // ai::candidate_action *ca = dynamic_cast<ai::candidate_action*>(*i);
3637  // ca->execute();
3638  //}
3639  }
3640 
3641  lua_rawset(L, -3); // setting the child table
3642  }
3643 
3644 
3645 }
3646 
3647 /**
3648  * Debug access to the ai tables
3649  * - Arg 1: int
3650  * - Ret 1: ai table
3651  */
3652 static int intf_debug_ai(lua_State *L)
3653 {
3654  if (!game_config::debug) { // This function works in debug mode only
3655  return 0;
3656  }
3657  int side;
3658  if(team* t = luaW_toteam(L, 1)) {
3659  side = t->side();
3660  } else {
3661  side = luaL_checkinteger(L, 1);
3662  }
3663  lua_pop(L, 1);
3664 
3666 
3667  // Bad, but works
3668  std::vector<ai::component*> engines = c->get_children("engine");
3669  ai::engine_lua* lua_engine = nullptr;
3670  for (std::vector<ai::component*>::const_iterator i = engines.begin(); i != engines.end(); ++i)
3671  {
3672  if ((*i)->get_name() == "lua")
3673  {
3674  lua_engine = dynamic_cast<ai::engine_lua *>(*i);
3675  }
3676  }
3677 
3678  // Better way, but doesn't work
3679  //ai::component* e = ai::manager::get_singleton().get_active_ai_holder_for_side_dbg(side).get_component(c, "engine[lua]");
3680  //ai::engine_lua* lua_engine = dynamic_cast<ai::engine_lua *>(e);
3681 
3682  if (lua_engine == nullptr)
3683  {
3684  //no lua engine is defined for this side.
3685  //so set up a dummy engine
3686 
3687  ai::ai_composite * ai_ptr = dynamic_cast<ai::ai_composite *>(c);
3688 
3689  assert(ai_ptr);
3690 
3691  ai::ai_context& ai_context = ai_ptr->get_ai_context();
3693 
3694  lua_engine = new ai::engine_lua(ai_context, cfg);
3695  LOG_LUA << "Created new dummy lua-engine for debug_ai(). \n";
3696 
3697  //and add the dummy engine as a component
3698  //to the manager, so we could use it later
3699  cfg.add_child("engine", lua_engine->to_config());
3700  ai::component_manager::add_component(c, "engine[]", cfg);
3701  }
3702 
3703  lua_engine->push_ai_table(); // stack: [-1: ai_context]
3704 
3705  lua_pushstring(L, "components");
3706  push_component(L, c); // stack: [-1: component tree; -2: ai context]
3707  lua_rawset(L, -3);
3708 
3709  return 1;
3710 }
3711 
3712 /// Allow undo sets the flag saying whether the event has mutated the game to false.
3714 {
3715  bool allow;
3716  t_string reason;
3717  // The extra iststring is required to prevent totstring from converting a bool value
3718  if(luaW_iststring(L, 1) && luaW_totstring(L, 1, reason)) {
3719  allow = false;
3720  } else {
3721  allow = luaW_toboolean(L, 1);
3722  luaW_totstring(L, 2, reason);
3723  }
3724  gamedata().set_allow_end_turn(allow, reason);
3725  return 0;
3726 }
3727 
3728 /// Allow undo sets the flag saying whether the event has mutated the game to false.
3730 {
3731  if(lua_isboolean(L, 1)) {
3732  play_controller_.pump().set_undo_disabled(!luaW_toboolean(L, 1));
3733  }
3734  else {
3735  play_controller_.pump().set_undo_disabled(false);
3736  }
3737  return 0;
3738 }
3739 
3741 {
3742  play_controller_.pump().set_action_canceled();
3743  return 0;
3744 }
3745 
3746 /// Adding new time_areas dynamically with Standard Location Filters.
3748 {
3749  log_scope("time_area");
3750 
3751  vconfig cfg(luaW_checkvconfig(L, 1));
3752  const std::string id = cfg["id"];
3753 
3754  std::set<map_location> locs;
3755  const terrain_filter filter(cfg, &game_state_);
3756  filter.get_locations(locs, true);
3757  config parsed_cfg = cfg.get_parsed_config();
3758  tod_man().add_time_area(id, locs, parsed_cfg);
3759  LOG_LUA << "Lua inserted time_area '" << id << "'\n";
3760  return 0;
3761 }
3762 
3763 /// Removing new time_areas dynamically with Standard Location Filters.
3765 {
3766  log_scope("remove_time_area");
3767 
3768  const char * id = luaL_checkstring(L, 1);
3769  tod_man().remove_time_area(id);
3770  LOG_LUA << "Lua removed time_area '" << id << "'\n";
3771 
3772  return 0;
3773 }
3774 
3775 /// Replacing the current time of day schedule.
3777 {
3778  vconfig cfg = luaW_checkvconfig(L, 1);
3779 
3780  if(cfg.get_children("time").empty()) {
3781  ERR_LUA << "attempted to to replace ToD schedule with empty schedule" << std::endl;
3782  } else {
3783  tod_man().replace_schedule(cfg.get_parsed_config());
3784  if (game_display_) {
3785  game_display_->new_turn();
3786  }
3787  LOG_LUA << "replaced ToD schedule\n";
3788  }
3789  return 0;
3790 }
3791 
3793 {
3794  if(!game_display_) {
3795  return 0;
3796  }
3797  std::string area_id;
3798  std::size_t area_i = 0;
3799  if (lua_isstring(L, 2)) {
3800  area_id = lua_tostring(L, 1);
3801  std::vector<std::string> area_ids = tod_man().get_area_ids();
3802  area_i = std::distance(area_ids.begin(), std::find(area_ids.begin(), area_ids.end(), area_id));
3803  if(area_i >= area_ids.size()) {
3804  return luaL_argerror(L, 1, "invalid time area ID");
3805  }
3806  }
3807  int is_num = false;
3808  int new_time = lua_tonumberx(L, 1, &is_num) - 1;
3809  const std::vector<time_of_day>& times = area_id.empty()
3810  ? tod_man().times()
3811  : tod_man().times(area_i);
3812  int num_times = times.size();
3813  if(!is_num) {
3814  std::string time_id = luaL_checkstring(L, 1);
3815  new_time = 0;
3816  for(const time_of_day& time : times) {
3817  if(time_id == time.id) {
3818  break;
3819  }
3820  new_time++;
3821  }
3822  if(new_time >= num_times) {
3823  return luaL_argerror(L, 1, "invalid time of day ID");
3824  }
3825  }
3826 
3827  if(new_time == 0 && num_times == 0) {
3828  //ignore this case, because we don't want code like set_current_time(get_current_time()) to fail if num_times is 0.
3829  return 0;
3830  }
3831  if(new_time < 0 || new_time >= num_times) {
3832  return luaL_argerror(L, 1, "invalid time of day index");
3833  }
3834 
3835  if(area_id.empty()) {
3836  tod_man().set_current_time(new_time);
3837  } else {
3838  tod_man().set_current_time(new_time, area_i);
3839  }
3840  return 0;
3841 }
3842 
3844 {
3845  int x = luaL_checkinteger(L, 1), y = luaL_checkinteger(L, 2);
3846 
3847  if (game_display_) {
3848  game_display_->scroll(x, y, true);
3849  game_display_->draw(true, true);
3850  }
3851 
3852  return 0;
3853 }
3854 
3855 namespace {
3856  struct lua_report_generator : reports::generator
3857  {
3858  lua_State *mState;
3859  std::string name;
3860  lua_report_generator(lua_State *L, const std::string &n)
3861  : mState(L), name(n) {}
3862  virtual config generate(reports::context & rc);
3863  };
3864 
3865  config lua_report_generator::generate(reports::context & /*rc*/)
3866  {
3867  lua_State *L = mState;
3868  config cfg;
3869  if (!luaW_getglobal(L, "wesnoth", "interface", "game_display", name))
3870  return cfg;
3871  if (!luaW_pcall(L, 0, 1)) return cfg;
3872  luaW_toconfig(L, -1, cfg);
3873  lua_pop(L, 1);
3874  return cfg;
3875  }
3876 }//unnamed namespace for lua_report_generator
3877 
3878 /**
3879  * Executes its upvalue as a theme item generator.
3880  */
3882 {
3883  reports::context temp_context = reports::context(board(), *game_display_, tod_man(), play_controller_.get_whiteboard(), play_controller_.get_mouse_handler_base());
3884  luaW_pushconfig(L, reports_.generate_report(m.c_str(), temp_context , true));
3885  return 1;
3886 }
3887 
3888 /**
3889  * Creates a field of the theme_items table and returns it (__index metamethod).
3890  */
3892 {
3893  char const *m = luaL_checkstring(L, 2);
3894  lua_cpp::push_closure(L, std::bind(&game_lua_kernel::impl_theme_item, this, _1, std::string(m)), 0);
3895  lua_pushvalue(L, 2);
3896  lua_pushvalue(L, -2);
3897  lua_rawset(L, 1);
3898  reports_.register_generator(m, new lua_report_generator(L, m));
3899  return 1;
3900 }
3901 
3902 /**
3903  * Sets a field of the theme_items table (__newindex metamethod).
3904  */
3906 {
3907  char const *m = luaL_checkstring(L, 2);
3908  lua_pushvalue(L, 2);
3909  lua_pushvalue(L, 3);
3910  lua_rawset(L, 1);
3911  reports_.register_generator(m, new lua_report_generator(L, m));
3912  return 0;
3913 }
3914 
3915 /**
3916  * Gets all the WML variables currently set.
3917  * - Ret 1: WML table
3918  */
3920  luaW_pushconfig(L, gamedata().get_variables());
3921  return 1;
3922 }
3923 
3924 /**
3925  * Teeleports a unit to a location.
3926  * Arg 1: unit
3927  * Arg 2: target location
3928  * Arg 3: bool (ignore_passability)
3929  * Arg 4: bool (clear_shroud)
3930  * Arg 5: bool (animate)
3931  */
3933 {
3934  events::command_disabler command_disabler;
3935  unit_ptr u = luaW_checkunit_ptr(L, 1, true);
3936  map_location dst = luaW_checklocation(L, 2);
3937  bool check_passability = !luaW_toboolean(L, 3);
3938  bool clear_shroud = luaW_toboolean(L, 4);
3939  bool animate = luaW_toboolean(L, 5);
3940 
3941  if (dst == u->get_location() || !map().on_board(dst)) {
3942  return 0;
3943  }
3944  const map_location vacant_dst = find_vacant_tile(dst, pathfind::VACANT_ANY, check_passability ? u.get() : nullptr);
3945  if (!map().on_board(vacant_dst)) {
3946  return 0;
3947  }
3948  // Clear the destination hex before the move (so the animation can be seen).
3949  actions::shroud_clearer clearer;
3950  if ( clear_shroud ) {
3951  clearer.clear_dest(vacant_dst, *u);
3952  }
3953 
3954  map_location src_loc = u->get_location();
3955 
3956  std::vector<map_location> teleport_path;
3957  teleport_path.push_back(src_loc);
3958  teleport_path.push_back(vacant_dst);
3959  unit_display::move_unit(teleport_path, u, animate);
3960 
3961  units().move(src_loc, vacant_dst);
3963 
3964  u = units().find(vacant_dst).get_shared_ptr();
3965  u->anim_comp().set_standing();
3966 
3967  if ( clear_shroud ) {
3968  // Now that the unit is visibly in position, clear the shroud.
3969  clearer.clear_unit(vacant_dst, *u);
3970  }
3971 
3972  if (map().is_village(vacant_dst)) {
3973  actions::get_village(vacant_dst, u->side());
3974  }
3975 
3976  game_display_->invalidate_unit_after_move(src_loc, vacant_dst);
3977  game_display_->draw();
3978 
3979  // Sighted events.
3980  clearer.fire_events();
3981  return 0;
3982 }
3983 
3984 /**
3985  * Removes a sound source by its ID
3986  * Arg 1: sound source ID
3987  */
3989 {
3990  soundsource::manager* man = play_controller_.get_soundsource_man();
3991  std::string id = luaL_checkstring(L, 1);
3992  man->remove(id);
3993  return 0;
3994 }
3995 
3996 /**
3997  * Add a new sound source
3998  * Arg 1: Table containing keyword arguments
3999  */
4001 {
4002  soundsource::manager* man = play_controller_.get_soundsource_man();
4003  config cfg = luaW_checkconfig(L, 1);
4004  try {
4005  soundsource::sourcespec spec(cfg);
4006  man->add(spec);
4007  man->update();
4008  } catch (const bad_lexical_cast &) {
4009  ERR_LUA << "Error when parsing sound_source config: invalid parameter." << std::endl;
4010  ERR_LUA << "sound_source config was: " << cfg.debug() << std::endl;
4011  ERR_LUA << "Skipping this sound source..." << std::endl;
4012  }
4013  return 0;
4014 }
4015 
4016 /**
4017  * Get an existing sound source
4018  * Arg 1: The sound source ID
4019  * Return: Config of sound source info, or nil if it didn't exist
4020  * This is a copy of the sound source info, so you need to call
4021  * add_sound_source again after changing it.
4022  */
4024 {
4025  soundsource::manager* man = play_controller_.get_soundsource_man();
4026  std::string id = luaL_checkstring(L, 1);
4027  config cfg = man->get(id);
4028  if(cfg.empty()) {
4029  return 0;
4030  }
4031  // Sound sources do not know their own string ID
4032  // Thus, we need to add this manually
4033  cfg["id"] = id;
4034  luaW_pushconfig(L, cfg);
4035  return 1;
4036 }
4037 
4038 /**
4039  * Logs a message
4040  * Arg 1: (optional) Logger; "wml" for WML errors or deprecations
4041  * Arg 2: Message
4042  * Arg 3: Whether to print to chat (always true if arg 1 is "wml")
4043  */
4045 {
4046  const std::string& logger = lua_isstring(L, 2) ? luaL_checkstring(L, 1) : "";
4047  const std::string& msg = lua_isstring(L, 2) ? luaL_checkstring(L, 2) : luaL_checkstring(L, 1);
4048 
4049  if(logger == "wml" || logger == "WML") {
4050  lg::wml_error() << msg << '\n';
4051  } else {
4052  bool in_chat = luaW_toboolean(L, -1);
4053  game_state_.events_manager_->pump().put_wml_message(logger,msg,in_chat);
4054  }
4055  return 0;
4056 }
4057 
4059 {
4060  int side = luaL_checknumber(L, 1);
4061  map_location loc = luaW_checklocation(L, 2);
4062  if(side < 1 || static_cast<std::size_t>(side) > teams().size()) {
4063  std::string error = "side " + std::to_string(side) + " does not exist";
4064  return luaL_argerror(L, 1, error.c_str());
4065  }
4066 
4067  team& t = board().get_team(side);
4068  lua_pushboolean(L, fog ? t.fogged(loc) : t.shrouded(loc));
4069  return 1;
4070 }
4071 
4072 /**
4073  * Implements the lifting and resetting of fog via WML.
4074  * Keeping affect_normal_fog as false causes only the fog override to be affected.
4075  * Otherwise, fog lifting will be implemented similar to normal sight (cannot be
4076  * individually reset and ends at the end of the turn), and fog resetting will, in
4077  * addition to removing overrides, extend the specified teams' normal fog to all
4078  * hexes.
4079  *
4080  * Arg 1: (optional) Side number, or list of side numbers
4081  * Arg 2: List of locations; each is a two-element array or a table with x and y keys
4082  * Arg 3: (optional) boolean
4083  */
4085 {
4086  bool affect_normal_fog = false;
4087  if(lua_isboolean(L, -1)) {
4088  affect_normal_fog = luaW_toboolean(L, -1);
4089  }
4090  std::set<int> sides;
4091  if(lua_isnumber(L, 1)) {
4092  sides.insert(lua_tonumber(L, 1));
4093  } else if(lua_istable(L, 1) && lua_istable(L, 2)) {
4094  const auto& v = lua_check<std::vector<int>>(L, 1);
4095  sides.insert(v.begin(), v.end());
4096  } else {
4097  for(const team& t : teams()) {
4098  sides.insert(t.side()+1);
4099  }
4100  }
4101  const auto& v_locs = lua_check<std::vector<map_location>>(L, lua_istable(L, 2) ? 2 : 1);
4102  std::set<map_location> locs(v_locs.begin(), v_locs.end());
4103 
4104  for(const int &side_num : sides) {
4105  if(side_num < 1 || static_cast<std::size_t>(side_num) > teams().size()) {
4106  continue;
4107  }
4108  team &t = board().get_team(side_num);
4109  if(!clear) {
4110  // Extend fog.
4111  t.remove_fog_override(locs);
4112  if(affect_normal_fog) {
4113  t.refog();
4114  }
4115  } else if(!affect_normal_fog) {
4116  // Force the locations clear of fog.
4117  t.add_fog_override(locs);
4118  } else {
4119  // Simply clear fog from the locations.
4120  for(const map_location &hex : locs) {
4121  t.clear_fog(hex);
4122  }
4123  }
4124  }
4125 
4126  // Flag a screen update.
4127  game_display_->recalculate_minimap();
4128  game_display_->invalidate_all();
4129  return 0;
4130 }
4131 
4132 // Invokes a synced command
4134 {
4135  const std::string name = luaL_checkstring(L, 1);
4136  auto it = synced_command::registry().find(name);
4137  config cmd;
4138  if(it == synced_command::registry().end()) {
4139  // Custom command
4140  if(!luaW_getglobal(L, "wesnoth", "custom_synced_commands", name)) {
4141  return luaL_argerror(L, 1, "Unknown synced command");
4142  }
4143  config& cmd_tag = cmd.child_or_add("custom_command");
4144  cmd_tag["name"] = name;
4145  if(!lua_isnoneornil(L, 2)) {
4146  cmd_tag.add_child("data", luaW_checkconfig(L, 2));
4147  }
4148  } else {
4149  // Built-in command
4150  cmd.add_child(name, luaW_checkconfig(L, 2));
4151  }
4152  // Now just forward to the WML action.
4153  luaW_getglobal(L, "wesnoth", "wml_actions", "do_command");
4154  luaW_pushconfig(L, cmd);
4155  luaW_pcall(L, 1, 0);
4156  return 0;
4157 }
4158 
4159 // END CALLBACK IMPLEMENTATION
4160 
4162  return game_state_.board_;
4163 }
4164 
4166  return game_state_.board_.units_;
4167 }
4168 
4169 std::vector<team> & game_lua_kernel::teams() {
4170  return game_state_.board_.teams_;
4171 }
4172 
4174  return game_state_.board_.map();
4175 }
4176 
4178  return game_state_.gamedata_;
4179 }
4180 
4182  return game_state_.tod_manager_;
4183 }
4184 
4186  return *queued_events_.top();
4187 }
4188 
4189 
4191  : lua_kernel_base()
4192  , game_display_(nullptr)
4193  , game_state_(gs)
4194  , play_controller_(pc)
4195  , reports_(reports_object)
4196  , level_lua_()
4197  , queued_events_()
4198  , map_locked_(0)
4199 {
4200  static game_events::queued_event default_queued_event("_from_lua", "", map_location(), map_location(), config());
4201  queued_events_.push(&default_queued_event);
4202 
4203  lua_State *L = mState;
4204 
4205  cmd_log_ << "Registering game-specific wesnoth lib functions...\n";
4206 
4207  // Put some callback functions in the scripting environment.
4208  static luaL_Reg const callbacks[] {
4209  { "add_known_unit", &intf_add_known_unit },
4210  { "create_animator", &dispatch<&game_lua_kernel::intf_create_animator> },
4211  { "eval_conditional", &intf_eval_conditional },
4212  { "get_era", &intf_get_era },
4213  { "get_resource", &intf_get_resource },
4214  { "get_traits", &intf_get_traits },
4215  { "get_viewing_side", &intf_get_viewing_side },
4216  { "invoke_synced_command", &intf_invoke_synced_command },
4217  { "modify_ai", &intf_modify_ai_old },
4218  { "set_music", &intf_set_music },
4219  { "sound_volume", &intf_sound_volume },
4220  { "unsynced", &intf_do_unsynced },
4221  { "add_event_handler", &dispatch<&game_lua_kernel::intf_add_event > },
4222  { "add_fog", &dispatch2<&game_lua_kernel::intf_toggle_fog, false > },
4223  { "add_time_area", &dispatch<&game_lua_kernel::intf_add_time_area > },
4224  { "add_sound_source", &dispatch<&game_lua_kernel::intf_add_sound_source > },
4225  { "allow_end_turn", &dispatch<&game_lua_kernel::intf_allow_end_turn > },
4226  { "allow_undo", &dispatch<&game_lua_kernel::intf_allow_undo > },
4227  { "cancel_action", &dispatch<&game_lua_kernel::intf_cancel_action > },
4228  { "clear_messages", &dispatch<&game_lua_kernel::intf_clear_messages > },
4229  { "end_turn", &dispatch<&game_lua_kernel::intf_end_turn > },
4230  { "end_level", &dispatch<&game_lua_kernel::intf_end_level > },
4231  { "find_cost_map", &dispatch<&game_lua_kernel::intf_find_cost_map > },
4232  { "find_path", &dispatch<&game_lua_kernel::intf_find_path > },
4233  { "find_reach", &dispatch<&game_lua_kernel::intf_find_reach > },
4234  { "find_vacant_tile", &dispatch<&game_lua_kernel::intf_find_vacant_tile > },
4235  { "fire_event", &dispatch2<&game_lua_kernel::intf_fire_event, false > },
4236  { "fire_event_by_id", &dispatch2<&game_lua_kernel::intf_fire_event, true > },
4237  { "get_all_vars", &dispatch<&game_lua_kernel::intf_get_all_vars > },
4238  { "get_end_level_data", &dispatch<&game_lua_kernel::intf_get_end_level_data > },
4239  { "get_locations", &dispatch<&game_lua_kernel::intf_get_locations > },
4240  { "get_map_size", &dispatch<&game_lua_kernel::intf_get_map_size > },
4241  { "get_sound_source", &dispatch<&game_lua_kernel::intf_get_sound_source > },
4242  { "get_terrain", &dispatch<&game_lua_kernel::intf_get_terrain > },
4243  { "get_terrain_info", &dispatch<&game_lua_kernel::intf_get_terrain_info > },
4244  { "get_time_of_day", &dispatch<&game_lua_kernel::intf_get_time_of_day > },
4245  { "get_max_liminal_bonus", &dispatch<&game_lua_kernel::intf_get_max_liminal_bonus > },
4246  { "get_variable", &dispatch<&game_lua_kernel::intf_get_variable > },
4247  { "get_villages", &dispatch<&game_lua_kernel::intf_get_villages > },
4248  { "get_village_owner", &dispatch<&game_lua_kernel::intf_get_village_owner > },
4249  { "label", &dispatch<&game_lua_kernel::intf_label > },
4250  { "log_replay", &dispatch<&game_lua_kernel::intf_log_replay > },
4251  { "log", &dispatch<&game_lua_kernel::intf_log > },
4252  { "match_location", &dispatch<&game_lua_kernel::intf_match_location > },
4253  { "message", &dispatch<&game_lua_kernel::intf_message > },
4254  { "open_help", &dispatch<&game_lua_kernel::intf_open_help > },
4255  { "play_sound", &dispatch<&game_lua_kernel::intf_play_sound > },
4256  { "print", &dispatch<&game_lua_kernel::intf_print > },
4257  { "redraw", &dispatch<&game_lua_kernel::intf_redraw > },
4258  { "remove_event_handler", &dispatch<&game_lua_kernel::intf_remove_event > },
4259  { "remove_fog", &dispatch2<&game_lua_kernel::intf_toggle_fog, true > },
4260  { "remove_time_area", &dispatch<&game_lua_kernel::intf_remove_time_area > },
4261  { "remove_sound_source", &dispatch<&game_lua_kernel::intf_remove_sound_source > },
4262  { "replace_schedule", &dispatch<&game_lua_kernel::intf_replace_schedule > },
4263  { "select_hex", &dispatch<&game_lua_kernel::intf_select_hex > },
4264  { "set_time_of_day", &dispatch<&game_lua_kernel::intf_set_time_of_day > },
4265  { "is_fogged", &dispatch2<&game_lua_kernel::intf_get_fog_or_shroud, true > },
4266  { "is_shrouded", &dispatch2<&game_lua_kernel::intf_get_fog_or_shroud, false > },
4267  { "set_end_campaign_credits", &dispatch<&game_lua_kernel::intf_set_end_campaign_credits > },
4268  { "set_end_campaign_text", &dispatch<&game_lua_kernel::intf_set_end_campaign_text > },
4269  { "create_side", &dispatch<&game_lua_kernel::intf_create_side > },
4270  { "set_next_scenario", &dispatch<&game_lua_kernel::intf_set_next_scenario > },
4271  { "set_terrain", &dispatch<&game_lua_kernel::intf_set_terrain > },
4272  { "set_variable", &dispatch<&game_lua_kernel::intf_set_variable > },
4273  { "set_village_owner", &dispatch<&game_lua_kernel::intf_set_village_owner > },
4274  { "simulate_combat", &dispatch<&game_lua_kernel::intf_simulate_combat > },
4275  { "synchronize_choice", &intf_synchronize_choice },
4276  { "synchronize_choices", &intf_synchronize_choices },
4277  { "terrain_mask", &dispatch<&game_lua_kernel::intf_terrain_mask > },
4278  { "teleport", &dispatch<&game_lua_kernel::intf_teleport > },
4279  { "place_shroud", &dispatch2<&game_lua_kernel::intf_shroud_op, true > },
4280  { "remove_shroud", &dispatch2<&game_lua_kernel::intf_shroud_op, false > },
4281  { nullptr, nullptr }
4282  };lua_getglobal(L, "wesnoth");
4283  if (!lua_istable(L,-1)) {
4284  lua_newtable(L);
4285  }
4286  luaL_setfuncs(L, callbacks, 0);
4287 
4288  if(play_controller_.get_classification().campaign_type == game_classification::CAMPAIGN_TYPE::TEST) {
4289  static luaL_Reg const test_callbacks[] {
4290  { "fire_wml_menu_item", &dispatch<&game_lua_kernel::intf_fire_wml_menu_item > },
4291  { nullptr, nullptr }
4292  };
4293  luaL_setfuncs(L, test_callbacks , 0);
4294  }
4295 
4296  lua_setglobal(L, "wesnoth");
4297 
4298  lua_getglobal(L, "gui");
4299  lua_pushcfunction(L, &dispatch<&game_lua_kernel::intf_gamestate_inspector>);
4300  lua_setfield(L, -2, "show_inspector");
4301  lua_pop(L, 1);
4302 
4303  // Create the getside metatable.
4305 
4306  // Create the gettype metatable.
4308 
4309  //Create the getrace metatable
4311 
4312  //Create the unit metatables
4315 
4316  // Create the vconfig metatable.
4318 
4319  // Create the unit_types table
4321 
4322  // Create the ai elements table.
4323  cmd_log_ << "Adding ai elements table...\n";
4324 
4326 
4327  // Create the current variable with its metatable.
4328  cmd_log_ << "Adding wesnoth current table...\n";
4329 
4330  lua_getglobal(L, "wesnoth");
4331  lua_newuserdata(L, 0);
4332  lua_createtable(L, 0, 2);
4333  lua_pushcfunction(L, &dispatch<&game_lua_kernel::impl_current_get>);
4334  lua_setfield(L, -2, "__index");
4335  lua_pushstring(L, "current config");
4336  lua_setfield(L, -2, "__metatable");
4337  lua_setmetatable(L, -2);
4338  lua_setfield(L, -2, "current");
4339  lua_pop(L, 1);
4340 
4341  // Add tovconfig to the WML module
4342  lua_getglobal(L, "wml");
4344  lua_setfield(L, -2, "tovconfig");
4345  lua_pop(L, 1);
4346 
4347  // Create the units module
4348  cmd_log_ << "Adding units module...\n";
4349  static luaL_Reg const unit_callbacks[] {
4350  {"advance", &intf_advance_unit},
4351  {"clone", &intf_copy_unit},
4352  {"erase", &dispatch<&game_lua_kernel::intf_erase_unit>},
4353  {"extract", &dispatch<&game_lua_kernel::intf_extract_unit>},
4354  {"matches", &dispatch<&game_lua_kernel::intf_match_unit>},
4355  {"select", &dispatch<&game_lua_kernel::intf_select_unit>},
4356  {"to_map", &dispatch<&game_lua_kernel::intf_put_unit>},
4357  {"to_recall", &dispatch<&game_lua_kernel::intf_put_recall_unit>},
4358  {"transform", &intf_transform_unit},
4359 
4360  {"ability", &dispatch<&game_lua_kernel::intf_unit_ability>},
4361  {"defense_on", &intf_unit_defense},
4362  {"jamming_on", &intf_unit_jamming_cost},
4363  {"movement_on", &intf_unit_movement_cost},
4364  {"resistance_against", intf_unit_resistance},
4365  {"vision_on", &intf_unit_vision_cost},
4366 
4367  {"add_modification", &intf_add_modification},
4368  {"remove_modifications", &intf_remove_modifications},
4369  // Static functions
4370  {"create", &intf_create_unit},
4371  {"find_on_map", &dispatch<&game_lua_kernel::intf_get_units>},
4372  {"find_on_recall", &dispatch<&game_lua_kernel::intf_get_recall_units>},
4373  {"get", &dispatch<&game_lua_kernel::intf_get_unit>},
4374  {"get_hovered", &dispatch<&game_lua_kernel::intf_get_displayed_unit>},
4375  { nullptr, nullptr }
4376  };
4377  lua_getglobal(L, "wesnoth");
4378  lua_newtable(L);
4379  luaL_setfuncs(L, unit_callbacks, 0);
4380  lua_setfield(L, -2, "units");
4381  lua_pop(L, 1);
4382 
4383  // Create sides module
4384  cmd_log_ << "Adding sides module...\n";
4385  static luaL_Reg const side_callbacks[] {
4386  { "is_enemy", &dispatch<&game_lua_kernel::intf_is_enemy> },
4387  { "matches", &dispatch<&game_lua_kernel::intf_match_side> },
4388  { "set_id", &dispatch<&game_lua_kernel::intf_set_side_id> },
4389  { "append_ai", &intf_append_ai },
4390  { "debug_ai", &intf_debug_ai },
4391  { "switch_ai", &intf_switch_ai },
4392  // Static functions
4393  { "find", &dispatch<&game_lua_kernel::intf_get_sides> },
4394  { "get", &dispatch<&game_lua_kernel::intf_get_side> },
4395  { nullptr, nullptr }
4396  };
4397  std::vector<lua_cpp::Reg> const cpp_side_callbacks {
4398  {"add_ai_component", std::bind(intf_modify_ai, _1, "add")},
4399  {"delete_ai_component", std::bind(intf_modify_ai, _1, "delete")},
4400  {"change_ai_component", std::bind(intf_modify_ai, _1, "change")},
4401  {nullptr, nullptr}
4402  };
4403 
4404  lua_getglobal(L, "wesnoth");
4405  lua_newtable(L);
4406  luaL_setfuncs(L, side_callbacks, 0);
4407  lua_cpp::set_functions(L, cpp_side_callbacks);
4408  lua_setfield(L, -2, "sides");
4409  lua_pop(L, 1);
4410 
4411  // Create the interface module
4412  cmd_log_ << "Adding interface module...\n";
4413  static luaL_Reg const intf_callbacks[] {
4414  {"add_hex_overlay", &dispatch<&game_lua_kernel::intf_add_tile_overlay>},
4415  {"remove_hex_overlay", &dispatch<&game_lua_kernel::intf_remove_tile_overlay>},
4416  {"color_adjust", &dispatch<&game_lua_kernel::intf_color_adjust>},
4417  {"delay", &dispatch<&game_lua_kernel::intf_delay>},
4418  {"deselect_hex", &dispatch<&game_lua_kernel::intf_deselect_hex>},
4419  {"highlight_hex", &dispatch<&game_lua_kernel::intf_highlight_hex>},
4420  {"float_label", &dispatch<&game_lua_kernel::intf_float_label>},
4421  {"get_displayed_unit", &dispatch<&game_lua_kernel::intf_get_displayed_unit>},
4422  {"get_hovered_hex", &dispatch<&game_lua_kernel::intf_get_mouseover_tile>},
4423  {"get_selected_hex", &dispatch<&game_lua_kernel::intf_get_selected_tile>},
4424  {"lock", &dispatch<&game_lua_kernel::intf_lock_view>},
4425  {"is_locked", &dispatch<&game_lua_kernel::intf_view_locked>},
4426  {"scroll", &dispatch<&game_lua_kernel::intf_scroll>},
4427  {"scroll_to_hex", &dispatch<&game_lua_kernel::intf_scroll_to_tile>},
4428  {"skip_messages", &dispatch<&game_lua_kernel::intf_skip_messages>},
4429  {"is_skipping_messages", &dispatch<&game_lua_kernel::intf_is_skipping_messages>},
4430  {"zoom", &dispatch<&game_lua_kernel::intf_zoom>},
4431  {"clear_menu_item", &dispatch<&game_lua_kernel::intf_clear_menu_item>},
4432  {"set_menu_item", &dispatch<&game_lua_kernel::intf_set_menu_item>},
4433  { nullptr, nullptr }
4434  };
4435  lua_getglobal(L, "wesnoth");
4436  lua_newtable(L);
4437  luaL_setfuncs(L, intf_callbacks, 0);
4438  lua_setfield(L, -2, "interface");
4439  lua_pop(L, 1);
4440 
4441  // Create the playlist table with its metatable
4443 
4444  // Create the wml_actions table.
4445  cmd_log_ << "Adding wml_actions table...\n";
4446 
4447  lua_getglobal(L, "wesnoth");
4448  lua_newtable(L);
4449  lua_setfield(L, -2, "wml_actions");
4450  lua_pop(L, 1);
4451 
4452  // Create the wml_conditionals table.
4453  cmd_log_ << "Adding wml_conditionals table...\n";
4454 
4455  lua_getglobal(L, "wesnoth");
4456  lua_newtable(L);
4457  lua_setfield(L, -2, "wml_conditionals");
4458  lua_pop(L, 1);
4462 
4463  // Create the effects table.
4464  cmd_log_ << "Adding effects table...\n";
4465 
4466  lua_getglobal(L, "wesnoth");
4467  lua_newtable(L);
4468  lua_setfield(L, -2, "effects");
4469  lua_pop(L, 1);
4470 
4471  // Create the custom_synced_commands table.
4472  cmd_log_ << "Adding custom_synced_commands table...\n";
4473 
4474  lua_getglobal(L, "wesnoth");
4475  lua_newtable(L);
4476  lua_setfield(L, -2, "custom_synced_commands");
4477  lua_pop(L, 1);
4478 
4479  // Create the game_events table.
4480  cmd_log_ << "Adding game_events table...\n";
4481 
4482  lua_getglobal(L, "wesnoth");
4483  lua_newtable(L);
4484  lua_setfield(L, -2, "game_events");
4486  lua_setfield(L, -2, "special_locations");
4487  lua_pop(L, 1);
4488 
4489  // Create the theme_items table.
4490  cmd_log_ << "Adding game_display table...\n";
4491 
4492  luaW_getglobal(L, "wesnoth", "interface");
4493  lua_newtable(L);
4494  lua_createtable(L, 0, 2);
4495  lua_pushcfunction(L, &dispatch<&game_lua_kernel::impl_theme_items_get>);
4496  lua_setfield(L, -2, "__index");
4497  lua_pushcfunction(L, &dispatch<&game_lua_kernel::impl_theme_items_set>);
4498  lua_setfield(L, -2, "__newindex");
4499  lua_setmetatable(L, -2);
4500  lua_setfield(L, -2, "game_display");
4501  lua_pop(L, 1);
4502 
4503  lua_settop(L, 0);
4504 
4505  for(const auto& handler : game_events::wml_action::registry())
4506  {
4507  set_wml_action(handler.first, handler.second);
4508  }
4509  luaW_getglobal(L, "wesnoth", "effects");
4510  for(const std::string& effect : unit::builtin_effects) {
4511  lua_pushstring(L, effect.c_str());
4513  lua_rawset(L, -3);
4514  }
4515  lua_settop(L, 0);
4516 }
4517 
4519 {
4520  lua_State *L = mState;
4521  assert(level_lua_.empty());
4522  level_lua_.append_children(level, "lua");
4523 
4524  //Create the races table.
4525  cmd_log_ << "Adding races table...\n";
4526 
4527  lua_settop(L, 0);
4528  lua_getglobal(L, "wesnoth");
4529  luaW_pushracetable(L);
4530  lua_setfield(L, -2, "races");
4531  lua_pop(L, 1);
4532 
4533  // Execute the preload scripts.
4534  cmd_log_ << "Running preload scripts...\n";
4535 
4536  game_config::load_config(game_lua_kernel::preload_config);
4537  for (const config &cfg : game_lua_kernel::preload_scripts) {
4538  run_lua_tag(cfg);
4539  }
4540  for (const config &cfg : level_lua_.child_range("lua")) {
4541  run_lua_tag(cfg);
4542  }
4543 }
4544 
4546  game_display_ = gd;
4547 }
4548 
4549 /// These are the child tags of [scenario] (and the like) that are handled
4550 /// elsewhere (in the C++ code).
4551 /// Any child tags not in this list will be passed to Lua's on_load event.
4552 static const std::array<std::string, 24> handled_file_tags {{
4553  "color_palette",
4554  "color_range",
4555  "display",
4556  "end_level_data",
4557  "era",
4558  "event",
4559  "generator",
4560  "label",
4561  "lua",
4562  "map",
4563  "menu_item",
4564  "modification",
4565  "modify_unit_type",
4566  "music",
4567  "options",
4568  "side",
4569  "sound_source",
4570  "story",
4571  "terrain_graphics",
4572  "time",
4573  "time_area",
4574  "tunnel",
4575  "undo_stack",
4576  "variables"
4577 }};
4578 
4579 static bool is_handled_file_tag(const std::string& s)
4580 {
4581  for(const std::string& t : handled_file_tags) {
4582  if (s == t) return true;
4583  }
4584 
4585  return false;
4586 }
4587 
4588 /**
4589  * Executes the game_events.on_load function and passes to it all the
4590  * scenario tags not yet handled.
4591  */
4593 {
4594  lua_State *L = mState;
4595 
4596  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_load"))
4597  return;
4598 
4599  lua_newtable(L);
4600  int k = 1;
4601  for (const config::any_child &v : level.all_children_range())
4602  {
4603  if (is_handled_file_tag(v.key)) continue;
4604  lua_createtable(L, 2, 0);
4605  lua_pushstring(L, v.key.c_str());
4606  lua_rawseti(L, -2, 1);
4607  luaW_pushconfig(L, v.cfg);
4608  lua_rawseti(L, -2, 2);
4609  lua_rawseti(L, -2, k++);
4610  }
4611 
4612  luaW_pcall(L, 1, 0, true);
4613 }
4614 
4615 /**
4616  * Executes the game_events.on_save function and adds to @a cfg the
4617  * returned tags. Also flushes the [lua] tags.
4618  */
4620 {
4621  lua_State *L = mState;
4622 
4623  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_save"))
4624  return;
4625 
4626  if (!luaW_pcall(L, 0, 1, false))
4627  return;
4628 
4629  config v;
4630  luaW_toconfig(L, -1, v);
4631  lua_pop(L, 1);
4632 
4633  for (;;)
4634  {
4636  if (i == v.ordered_end()) break;
4637  if (is_handled_file_tag(i->key))
4638  {
4639  /*
4640  * It seems the only tags appearing in the config v variable here
4641  * are the core-lua-handled (currently [item] and [objectives])
4642  * and the extra UMC ones.
4643  */
4644  const std::string m = "Tag is already used: [" + i->key + "]";
4645  log_error(m.c_str());
4646  v.erase(i);
4647  continue;
4648  }
4649  cfg.splice_children(v, i->key);
4650  }
4651 }
4652 
4653 /**
4654  * Executes the game_events.on_event function.
4655  * Returns false if there was no lua handler for this event
4656  */
4658 {
4659  lua_State *L = mState;
4660 
4661  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_event"))
4662  return false;
4663 
4664  queued_event_context dummy(&ev, queued_events_);
4665  lua_pushstring(L, ev.name.c_str());
4666  luaW_pcall(L, 1, 0, false);
4667  return true;
4668 }
4669 
4671 {
4672  lua_State *L = mState;
4673 
4674  if (!luaW_getglobal(L, "wesnoth", "custom_synced_commands", name)) {
4675  return;
4676  }
4677  luaW_pushconfig(L, cfg);
4678  luaW_pcall(L, 1, 0, false);
4679 }
4680 
4681 /**
4682  * Applies its upvalue as an effect
4683  * Arg 1: The unit to apply to
4684  * Arg 3: The [effect] tag contents
4685  * Arg 3: If false, only build description
4686  * Return: The description of the effect
4687  */
4689 {
4690  std::string which_effect = lua_tostring(L, lua_upvalueindex(1));
4691  bool need_apply = luaW_toboolean(L, lua_upvalueindex(2));
4692  // Argument 1 is the implicit "self" argument, which isn't needed here
4693  lua_unit u(luaW_checkunit(L, 2));
4694  config cfg = luaW_checkconfig(L, 3);
4695 
4696  // The times= key is supposed to be ignored by the effect function.
4697  // However, just in case someone doesn't realize this, we will set it to 1 here.
4698  cfg["times"] = 1;
4699 
4700  if(need_apply) {
4701  u->apply_builtin_effect(which_effect, cfg);
4702  return 0;
4703  } else {
4704  std::string description = u->describe_builtin_effect(which_effect, cfg);
4705  lua_pushstring(L, description.c_str());
4706  return 1;
4707  }
4708 }
4709 
4710 /**
4711 * Registers a function for use as an effect handler.
4712 */
4714 {
4715  lua_State *L = mState;
4716 
4717  // The effect name is at the top of the stack
4718  int str_i = lua_gettop(L);
4719  lua_newtable(L); // The functor table
4720  lua_newtable(L); // The functor metatable
4721  lua_pushstring(L, "__call");
4722  lua_pushvalue(L, str_i);
4723  lua_pushboolean(L, true);
4724  lua_pushcclosure(L, &dispatch<&game_lua_kernel::cfun_builtin_effect>, 2);
4725  lua_rawset(L, -3); // Set the call metafunction
4726  lua_pushstring(L, "__descr");
4727  lua_pushvalue(L, str_i);
4728  lua_pushboolean(L, false);
4729  lua_pushcclosure(L, &dispatch<&game_lua_kernel::cfun_builtin_effect>, 2);
4730  lua_rawset(L, -3); // Set the descr "metafunction"
4731  lua_setmetatable(L, -2); // Apply the metatable to the functor table
4732 }
4733 
4734 
4735 /**
4736  * Executes its upvalue as a wml action.
4737  */
4739 {
4742 
4743  vconfig vcfg = luaW_checkvconfig(L, 1);
4744  h(get_event_info(), vcfg);
4745  return 0;
4746 }
4747 
4748 /**
4749  * Registers a function for use as an action handler.
4750  */
4752 {
4753  lua_State *L = mState;
4754 
4755  lua_getglobal(L, "wesnoth");
4756  lua_pushstring(L, "wml_actions");
4757  lua_rawget(L, -2);
4758  lua_pushstring(L, cmd.c_str());
4759  lua_pushlightuserdata(L, reinterpret_cast<void *>(h));
4760  lua_pushcclosure(L, &dispatch<&game_lua_kernel::cfun_wml_action>, 1);
4761  lua_rawset(L, -3);
4762  lua_pop(L, 2);
4763 }
4764 
4765 using wml_conditional_handler = bool(*)(const vconfig&);
4766 
4767 /**
4768  * Executes its upvalue as a wml condition and returns the result.
4769  */
4771 {
4774 
4775  vconfig vcfg = luaW_checkvconfig(L, 1);
4776  lua_pushboolean(L, h(vcfg));
4777  return 1;
4778 }
4779 
4780 /**
4781  * Registers a function for use as a conditional handler.
4782  */
4784 {
4785  lua_State *L = mState;
4786 
4787  lua_getglobal(L, "wesnoth");
4788  lua_pushstring(L, "wml_conditionals");
4789  lua_rawget(L, -2);
4790  lua_pushstring(L, cmd.c_str());
4791  lua_pushlightuserdata(L, reinterpret_cast<void *>(h));
4793  lua_rawset(L, -3);
4794  lua_pop(L, 2);
4795 }
4796 
4797 /**
4798  * Runs a command from an event handler.
4799  * @return true if there is a handler for the command.
4800  * @note @a cfg should be either volatile or long-lived since the Lua
4801  * code may grab it for an arbitrary long time.
4802  */
4804  const game_events::queued_event& ev)
4805 {
4806  lua_State *L = mState;
4807 
4808 
4809  if (!luaW_getglobal(L, "wesnoth", "wml_actions", cmd))
4810  return false;
4811 
4812  queued_event_context dummy(&ev, queued_events_);
4813  luaW_pushvconfig(L, cfg);
4814  luaW_pcall(L, 1, 0, true);
4815  return true;
4816 }
4817 
4818 
4819 /**
4820  * Evaluates a WML conidition.
4821  *
4822  * @returns Whether the condition passed.
4823  * @note @a cfg should be either volatile or long-lived since the Lua
4824  * code may grab it for an arbitrarily long time.
4825  */
4827 {
4828  lua_State* L = mState;
4829 
4830  // If an invalid coniditional tag is used, consider it a pass.
4831  if(!luaW_getglobal(L, "wesnoth", "wml_conditionals", cmd)) {
4832  lg::wml_error() << "unknown conditional wml: [" << cmd << "]\n";
4833  return true;
4834  }
4835 
4836  luaW_pushvconfig(L, cfg);
4837 
4838  // Any runtime error is considered a fail.
4839  if(!luaW_pcall(L, 1, 1, true)) {
4840  return false;
4841  }
4842 
4843  bool b = luaW_toboolean(L, -1);
4844 
4845  lua_pop(L, 1);
4846  return b;
4847 }
4848 
4849 
4850 /**
4851 * Runs a script from a location filter.
4852 * The script is an already compiled function given by its name.
4853 */
4854 bool game_lua_kernel::run_filter(char const *name, const map_location& l)
4855 {
4858  return run_filter(name, 2);
4859 }
4860 
4861 /**
4862 * Runs a script from a location filter.
4863 * The script is an already compiled function given by its name.
4864 */
4865 bool game_lua_kernel::run_filter(char const *name, const team& t)
4866 {
4867  //TODO: instead of passing the lua team object we coudl also jsut pass its
4868  // number. then we wouldn't need this const cast.
4869  luaW_pushteam(mState, const_cast<team&>(t));
4870  return run_filter(name, 1);
4871 }
4872 /**
4873 * Runs a script from a unit filter.
4874 * The script is an already compiled function given by its name.
4875 */
4876 bool game_lua_kernel::run_filter(char const *name, const unit& u)
4877 {
4878  lua_State *L = mState;
4879  lua_unit* lu = luaW_pushlocalunit(L, const_cast<unit&>(u));
4880  // stack: unit
4881  // put the unit to the stack twice to prevent gc.
4882  lua_pushvalue(L, -1);
4883  // stack: unit, unit
4884  bool res = run_filter(name, 1);
4885  // stack: unit
4886  lu->clear_ref();
4887  lua_pop(L, 1);
4888  return res;
4889 }
4890 /**
4891 * Runs a script from a filter.
4892 * The script is an already compiled function given by its name.
4893 */
4894 bool game_lua_kernel::run_filter(char const *name, int nArgs)
4895 {
4896  map_locker(this);
4897  lua_State *L = mState;
4898  // Get the user filter by name.
4899  const std::vector<std::string>& path = utils::split(name, '.', utils::STRIP_SPACES);
4900  if (!luaW_getglobal(L, path))
4901  {
4902  std::string message = std::string() + "function " + name + " not found";
4903  log_error(message.c_str(), "Lua SUF Error");
4904  //we pushed nothing and can safeley return.
4905  return false;
4906  }
4907  lua_insert(L, -nArgs - 1);
4908 
4909  if (!luaW_pcall(L, nArgs, 1)) return false;
4910 
4911  bool b = luaW_toboolean(L, -1);
4912  lua_pop(L, 1);
4913  return b;
4914 }
4915 
4916 std::string game_lua_kernel::apply_effect(const std::string& name, unit& u, const config& cfg, bool need_apply)
4917 {
4918  lua_State *L = mState;
4919  int top = lua_gettop(L);
4920  std::string descr;
4921  // Stack: nothing
4922  lua_unit* lu = luaW_pushlocalunit(L, u);
4923  // Stack: unit
4924  // (Note: The unit needs to be on the stack twice to prevent untimely GC.)
4925  luaW_pushconfig(L, cfg);
4926  // Stack: unit, cfg
4927  if(luaW_getglobal(L, "wesnoth", "effects", name)) {
4928  map_locker(this);
4929  // Stack: unit, cfg, effect
4930  if(lua_istable(L, -1)) {
4931  // Effect is implemented by a table with __call and __descr
4932  if(need_apply) {
4933  lua_pushvalue(L, -1);
4934  // Stack: unit, cfg, effect, effect
4935  lua_pushvalue(L, top + 1);
4936  // Stack: unit, cfg, effect, effect, unit
4937  lua_pushvalue(L, top + 2);
4938  // Stack: unit, cfg, effect, effect, unit, cfg
4939  luaW_pcall(L, 2, 0);
4940  // Stack: unit, cfg, effect
4941  }
4942  if(luaL_getmetafield(L, -1, "__descr")) {
4943  // Stack: unit, cfg, effect, __descr
4944  if(lua_isstring(L, -1)) {
4945  // __descr was a static string
4946  descr = lua_tostring(L, -1);
4947  } else {
4948  lua_pushvalue(L, -2);
4949  // Stack: unit, cfg, effect, __descr, effect
4950  lua_pushvalue(L, top + 1);
4951  // Stack: unit, cfg, effect, __descr, effect, unit
4952  lua_pushvalue(L, top + 2);
4953  // Stack: unit, cfg, effect, __descr, effect, unit, cfg
4954  luaW_pcall(L, 3, 1);
4955  if(lua_isstring(L, -1) && !lua_isnumber(L, -1)) {
4956  descr = lua_tostring(L, -1);
4957  } else {
4958  ERR_LUA << "Effect __descr metafunction should have returned a string, but instead returned ";
4959  if(lua_isnone(L, -1)) {
4960  ERR_LUA << "nothing";
4961  } else {
4962  ERR_LUA << lua_typename(L, lua_type(L, -1));
4963  }
4964  }
4965  }
4966  }
4967  } else if(need_apply) {
4968  // Effect is assumed to be a simple function; no description is provided
4969  lua_pushvalue(L, top + 1);
4970  // Stack: unit, cfg, effect, unit
4971  lua_pushvalue(L, top + 2);
4972  // Stack: unit, cfg, effect, unit, cfg
4973  luaW_pcall(L, 2, 0);
4974  // Stack: unit, cfg
4975  }
4976  }
4977  lua_settop(L, top);
4978  lu->clear_ref();
4979  return descr;
4980 }
4981 
4983 {
4984  return ai::lua_ai_context::create(mState,code,engine);
4985 }
4986 
4988 {
4989  return ai::lua_ai_action_handler::create(mState,code,context);
4990 }
4991 
4993 {
4994  lua_State *L = mState;
4995 
4996  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_mouse_move")) {
4997  return;
4998  }
4999  lua_push(L, loc.wml_x());
5000  lua_push(L, loc.wml_y());
5001  luaW_pcall(L, 2, 0, false);
5002  return;
5003 }
5004 
5006 {
5007  lua_State *L = mState;
5008 
5009  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_mouse_action")) {
5010  return;
5011  }
5012  lua_push(L, loc.wml_x());
5013  lua_push(L, loc.wml_y());
5014  luaW_pcall(L, 2, 0, false);
5015  return;
5016 }
const_attack_ptr weapon
The weapon used by the unit to attack the opponent, or nullptr if there is none.
Definition: attack.hpp:52
void set_wml_y(int v)
Definition: location.hpp:161
bool luaW_checkvariable(lua_State *L, variable_access_create &v, int n)
Definition: lua_common.cpp:923
int dispatch(lua_State *L)
#define modify_bool_attrib(name, accessor)
Definition: lua_common.hpp:339
bool luaW_tableget(lua_State *L, int index, const char *key)
Definition: lua_common.cpp:966
play_controller * controller
Definition: resources.cpp:21
int intf_get_terrain_info(lua_State *L)
Gets details about a terrain.
static int intf_transform_unit(lua_State *L)
Changes a unit to the given unit type.
#define lua_isnoneornil(L, n)
Definition: lua.h:359
void wait_for_end() const
Definition: animation.cpp:1442
unsigned int end_text_duration
for how long the end-of-campaign text is shown
bool empty() const
Tests for an attribute that either was never set or was set to "".
LUA_API void lua_pushlightuserdata(lua_State *L, void *p)
Definition: lapi.cpp:565
static int impl_end_level_data_get(lua_State *L)
LUALIB_API void * luaL_checkudata(lua_State *L, int ud, const char *tname)
Definition: lauxlib.cpp:333
config get_user_choice(const std::string &name, const user_choice &uch, int side=0)
std::stack< game_events::queued_event const *> queued_events_
Game board class.
Definition: game_board.hpp:50
LUA_API void lua_createtable(lua_State *L, int narray, int nrec)
Definition: lapi.cpp:684
#define lua_pushcfunction(L, f)
Definition: lua.h:350
static int intf_advance_unit(lua_State *L)
Advances a unit if the unit has enough xp.
static int intf_get_era(lua_State *L)
Gets a table for an era tag.
static int special_locations_pairs(lua_State *L)
virtual std::string get_id() const =0
utils::string_view luaW_tostring(lua_State *L, int index)
Definition: lua_common.cpp:978
int map_locked_
A value != 0 means that the shouldn&#39;t remove any units from the map, usually because we are currently...
std::string apply_effect(const std::string &name, unit &u, const config &cfg, bool need_apply)
bool is_odd(T num)
Definition: math.hpp:35
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:420
lua_unit * luaW_pushunit(lua_State *L, Args... args)
Definition: lua_unit.hpp:115
bool on_map() const
Definition: lua_unit.hpp:99
int h() const
Effective map height, in hexes.
Definition: map.hpp:128
bool end_credits
whether to show the standard credits at the end
void set_shroud(bool shroud)
Definition: team.hpp:326
bool is_castle() const
Definition: terrain.hpp:142
double untouched
Resulting chance we were not hit by this opponent (important if it poisons)
std::vector< double > hp_dist
Resulting probability distribution (might be not as large as max_hp)
bool update_locked() const
Whether the screen has been &#39;locked&#39; or not.
Definition: video.cpp:349
void show_help(const std::string &show_topic, int xloc, int yloc)
Open the help browser, show topic with id show_topic.
Definition: help.cpp:114
entity_location loc2
Definition: pump.hpp:65
LUA_API lua_Number lua_tonumberx(lua_State *L, int idx, int *pisnum)
Definition: lapi.cpp:345
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:88
int intf_remove_sound_source(lua_State *L)
Removes a sound source by its ID Arg 1: sound source ID.
int intf_allow_end_turn(lua_State *)
Allow undo sets the flag saying whether the event has mutated the game to false.
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:921
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:1159
void start_animations()
Definition: animation.cpp:1383
int intf_find_path(lua_State *L)
Finds a path between two locations.
const terrain_code NONE_TERRAIN
Definition: translation.hpp:59
bool luaW_tovconfig(lua_State *L, int index, vconfig &vcfg)
Gets an optional vconfig from either a table or a userdata.
Definition: lua_common.cpp:836
std::string register_metatables(lua_State *L)
Definition: lua_unit.cpp:654
vconfig child(const std::string &key) const
Returns a child of *this whose key is key.
Definition: variable.cpp:288
int intf_set_end_campaign_credits(lua_State *L)
void reshroud()
Definition: team.hpp:324
const t_string & description() const
Definition: terrain.hpp:49
LUALIB_API lua_Number luaL_checknumber(lua_State *L, int arg)
Definition: lauxlib.cpp:408
game_display * game_display_
void luaW_pushconfig(lua_State *L, const config &cfg)
Converts a config object to a Lua table pushed at the top of the stack.
Definition: lua_common.cpp:730
LUA_API void lua_settop(lua_State *L, int idx)
Definition: lapi.cpp:172
int intf_fire_event(lua_State *L, const bool by_id)
Fires an event.
#define lua_isnone(L, n)
Definition: lua.h:358
int intf_get_time_of_day(lua_State *L)
Gets time of day information.
int intf_get_unit(lua_State *)
Gets the unit at the given location or with the given id.
LUA_API int lua_type(lua_State *L, int idx)
Definition: lapi.cpp:251
int village_support
Definition: game_config.cpp:55
bool luaW_pcall(lua_State *L, int nArgs, int nRets, bool allow_wml_error)
Calls a Lua function stored below its nArgs arguments at the top of the stack.
void luaW_pushteam(lua_State *L, team &tm)
Create a full userdata containing a pointer to the team.
Definition: lua_team.cpp:340
std::string era()
Definition: game.cpp:712
std::string plague_type
The plague type used by the attack, if any.
Definition: attack.hpp:84
This class represents a single unit of a specific type.
Definition: unit.hpp:129
int dummy
Definition: lstrlib.cpp:1125
game_classification * classification
Definition: resources.cpp:34
int intf_get_variable(lua_State *L)
Gets a WML variable.
tod_color color
The color modifications that should be made to the game board to reflect the time of day...
int movement_cost(const t_translation::terrain_code &terrain) const
Get the unit&#39;s movement cost on a particular terrain.
Definition: unit.hpp:1426
int intf_match_location(lua_State *L)
Matches a location against the given filter.
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
void advance_to(const unit_type &t, bool use_traits=false)
Advances this unit to another type.
Definition: unit.cpp:891
std::vector< int > get_sides_vector(const vconfig &cfg)
Gets a vector of sides from side= attribute in a given config node.
Various functions implementing vision (through fog of war and shroud).
int luaW_type_error(lua_State *L, int narg, const char *tname)
bool run_filter(char const *name, const unit &u)
Runs a script from a unit filter.
int impl_theme_items_get(lua_State *L)
Creates a field of the theme_items table and returns it (__index metamethod).
int intf_replace_schedule(lua_State *l)
Replacing the current time of day schedule.
static int special_locations_len(lua_State *L)
bool play_stage()
Play the turn - strategy.
Definition: stage.cpp:56
void set_clip_rect(const SDL_Rect &r)
unit & luaW_checkunit(lua_State *L, int index, bool only_on_map)
Converts a Lua value to a unit pointer.
Definition: lua_unit.cpp:194
static manager & get_singleton()
Definition: manager.hpp:151
config_array_view traits() const
Definition: types.hpp:378
LUA_API void lua_pushboolean(lua_State *L, int b)
Definition: lapi.cpp:557
LUA_API int lua_rawgeti(lua_State *L, int idx, lua_Integer n)
Definition: lapi.cpp:658
Various functions that implement attacks and attack calculations.
int impl_end_level_data_set(lua_State *)
Variant for storing WML attributes.
int intf_view_locked(lua_State *L)
Gets whether gamemap scrolling is disabled for the user.
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
bool luaW_isunit(lua_State *L, int index)
Test if a Lua value is a unit.
Definition: lua_unit.cpp:116
void set_next_scenario(const std::string &next_scenario)
Definition: game_data.hpp:94
bool clear_fog(const map_location &loc)
Definition: team.hpp:323
void add_log_data(const std::string &key, const std::string &var)
Definition: replay.cpp:310
virtual std::vector< component * > get_children(const std::string &type)
Definition: component.cpp:111
std::vector< team > & teams()
static const char animatorKey[]
static l_noret error(LoadState *S, const char *why)
Definition: lundump.cpp:39
int intf_set_terrain(lua_State *L)
Sets a terrain code.
int intf_log(lua_State *L)
Logs a message Arg 1: (optional) Logger; "wml" for WML errors or deprecations Arg 2: Message Arg 3: W...
logger & info()
Definition: log.cpp:91
#define a
config_array_view child_range(config_key_type key) const
static map & registry()
using static function variable instead of static member variable to prevent static initialization fia...
int intf_clear_messages(lua_State *)
Removes all messages from the chat window.
Definition: video.hpp:31
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:412
void refog()
Definition: team.hpp:325
int intf_play_sound(lua_State *L)
Plays a sound, possibly repeated.
int next_player_number_
Definition: game_state.hpp:58
int intf_terrain_mask(lua_State *L)
Reaplces part of the map.
static int impl_animator_get(lua_State *L)
bool have_location(const vconfig &cfg)
int intf_label(lua_State *L)
static int special_locations_newindex(lua_State *L)
bool has_attribute(const std::string &key) const
< Synonym for operator[]
Definition: variable.hpp:106
map_location find_vacant_tile(const map_location &loc, VACANT_TILE_TYPE vacancy, const unit *pass_check, const team *shroud_check, const game_board *board)
Function that will find a location on the board that is as near to loc as possible, but which is unoccupied by any units.
Definition: pathfind.cpp:54
LUA_API void lua_rawseti(lua_State *L, int idx, lua_Integer n)
Definition: lapi.cpp:817
LUALIB_API int luaL_getmetafield(lua_State *L, int obj, const char *event)
Definition: lauxlib.cpp:772
LUA_API int lua_gettop(lua_State *L)
Definition: lapi.cpp:167
child_itors child_range(config_key_type key)
Definition: config.cpp:362
std::string register_table(lua_State *L)
std::string id
Definition: time_of_day.hpp:91
int border_size() const
Size of the map border.
Definition: map.hpp:131
int intf_extract_unit(lua_State *L)
Extracts a unit from the map or a recall list and gives it to Lua.
double average_hp(unsigned int healing=0) const
What&#39;s the average hp (weighted average of hp_dist).
const map_location & filter_loc() const
bool luaW_pushvariable(lua_State *L, variable_access_const &v)
Definition: lua_common.cpp:895
static int intf_copy_unit(lua_State *L)
Copies a unit.
void remove_floating_label(int handle)
removes the floating label given by &#39;handle&#39; from the screen
std::string register_metatable(lua_State *L)
static int special_locations_next(lua_State *L)
int intf_get_all_vars(lua_State *L)
Gets all the WML variables currently set.
LUA_API int lua_getglobal(lua_State *L, const char *name)
Definition: lapi.cpp:605
int intf_find_cost_map(lua_State *L)
Is called with one or more units and builds a cost map.
void clear(const std::string &key)
Definition: general.cpp:204
virtual const gamemap & map() const override
Definition: game_board.hpp:109
int lawful_bonus
The % bonus lawful units receive.
Definition: time_of_day.hpp:84
#define return_string_attrib(name, accessor)
Definition: lua_common.hpp:217
dest_vect destinations
Definition: pathfind.hpp:99
unit_ptr clone() const
Definition: unit.hpp:211
#define lua_tointeger(L, i)
Definition: lua.h:342
int intf_set_time_of_day(lua_State *L)
int wml_x() const
Definition: location.hpp:157
virtual config to_config() const
Serialize to config.
Definition: engine_lua.cpp:388
A terrain string which is converted to a terrain is a string with 1 or 2 layers the layers are separa...
Definition: translation.hpp:50
static int special_locations_index(lua_State *L)
static lua_ai_context * create(lua_State *L, char const *code, engine_lua *engine)
Definition: core.cpp:995
LUA_API int lua_rawget(lua_State *L, int idx)
Definition: lapi.cpp:647
Composite AI stages.
std::string image
The image to be displayed in the game status.
Definition: time_of_day.hpp:88
unit_type_data unit_types
Definition: types.cpp:1378
void set_wml_x(int v)
Definition: location.hpp:160
int intf_get_fog_or_shroud(lua_State *L, bool fog)
static int cfun_wml_condition(lua_State *L)
Executes its upvalue as a wml condition and returns the result.
bool prescenario_save
Should a prescenario be created the next game?
int intf_set_village_owner(lua_State *L)
Sets the owner of a village.
lua_unit * luaW_pushlocalunit(lua_State *L, unit &u)
Pushes a private unit on the stack.
Definition: lua_unit.cpp:215
const color_t LABEL_COLOR
int intf_unit_ability(lua_State *L)
Returns true if the unit has the given ability enabled.
int intf_match_unit(lua_State *L)
Matches a unit against the given filter.
int intf_set_next_scenario(lua_State *L)
void push_builtin_effect()
Registers a function for use as an effect handler.
static CVideo & get_singleton()
Definition: video.hpp:48
std::string name
Definition: pump.hpp:62
Replay control code.
#define h
static void msg(const char *act, debug_info &i, const char *to="", const char *result="")
Definition: debugger.cpp:109
#define lua_tonumber(L, i)
Definition: lua.h:341
config & child_or_add(config_key_type key)
Definition: config.cpp:466
advance_unit_params & fire_events(bool value)
Definition: advancement.hpp:45
bool replay_save
Should a replay save be made?
void remove(const std::string &id)
Definition: soundsource.cpp:65
std::string save_id_or_number() const
Definition: team.hpp:232
void custom_command(const std::string &, const config &)
Additional functionality for a non-const variable_info.
bool slows
Attack slows opponent when it hits.
Definition: attack.hpp:57
int intf_skip_messages(lua_State *L)
Set whether to skip messages Arg 1 (optional) - boolean.
void set_font_size(int font_size)
LUA_API int lua_isuserdata(lua_State *L, int idx)
Definition: lapi.cpp:289
const std::string & editor_image() const
Definition: terrain.hpp:46
LUA_API void lua_pushcclosure(lua_State *L, lua_CFunction fn, int n)
Definition: lapi.cpp:532
int intf_scroll(lua_State *L)
virtual void draw()
Draws invalidated items.
Definition: display.cpp:2475
int impl_theme_items_set(lua_State *L)
Sets a field of the theme_items table (__newindex metamethod).
void append_children(const config &cfg)
Adds children from cfg.
Definition: config.cpp:241
#define return_vector_string_attrib(name, accessor)
Definition: lua_common.hpp:268
int intf_get_max_liminal_bonus(lua_State *L)
Gets the max liminal bonus.
std::string str
Definition: statement.cpp:110
static bool is_handled_file_tag(const std::string &s)
int intf_get_sides(lua_State *L)
Returns a proxy table array for all sides matching the given SSF.
void lua_push(lua_State *L, const T &val)
Definition: push_check.hpp:400
void add_unit(const unit &u, bool use_max_moves=true)
Adds a units cost map to cost_map (increments the elements in cost_map)
Definition: pathfind.cpp:911
int drain_constant
Base HP drained regardless of damage dealt.
Definition: attack.hpp:79
an object to leave the synced context during draw or unsynced wml items when we don’t know whether w...
int(game_lua_kernel::* member_callback2)(lua_State *, bool)
int intf_gamestate_inspector(lua_State *)
-file sdl_utils.hpp
int impl_game_config_set(lua_State *L) override
Sets some game_config data (__newindex metamethod).
void(* handler)(const queued_event &, const vconfig &)
Definition: action_wml.hpp:49
map_location luaW_checklocation(lua_State *L, int index)
Converts an optional table or pair of integers to a map location object.
Definition: lua_common.cpp:722
Definitions for the interface to Wesnoth Markup Language (WML).
bool empty() const
Definition: variable.hpp:107
const game_events::queued_event & get_event_info()
LUA_API int lua_absindex(lua_State *L, int idx)
Definition: lapi.cpp:160
std::shared_ptr< unit > unit_ptr
Definition: ptr.hpp:28
void load_config(const config &v)
static synced_state get_synced_state()
unsigned int chance_to_hit
Effective chance to hit as a percentage (all factors accounted for).
Definition: attack.hpp:75
int rest_heal_amount
Definition: game_config.cpp:61
std::map< int, config > get_user_choice_multiple_sides(const std::string &name, const user_choice &uch, std::set< int > sides)
Performs a choice for multiple sides for WML events.
static unit_ptr create(const config &cfg, bool use_traits=false, const vconfig *vcfg=nullptr)
Initializes a unit from a config.
Definition: unit.hpp:191
const_attr_itors attribute_range() const
Definition: config.cpp:809
LUA_API void * lua_newuserdata(lua_State *L, size_t size)
Definition: lapi.cpp:1184
A single unit type that the player may recruit.
Definition: types.hpp:44
int intf_get_locations(lua_State *L)
Gets all the locations matching a given filter.
game_data * gamedata
Definition: resources.cpp:22
int intf_log_replay(lua_State *L)
advance_unit_params & animate(bool value)
Definition: advancement.hpp:46
Unit and team statistics.
#define lua_pop(L, n)
Definition: lua.h:344