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