-
-
Notifications
You must be signed in to change notification settings - Fork 995
/
wml-tags.lua
1447 lines (1253 loc) · 46 KB
/
wml-tags.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--! #textdomain wesnoth
function wesnoth.game_events.on_load(cfg)
if #cfg == 0 then return end
local t = {}
for i = 1,#cfg do t[i] = string.format("[%s]", cfg[i][1]) end
error(string.format("~wml:%s not supported at scenario toplevel", table.concat(t, ', ')), 0)
end
function wesnoth.game_events.on_save()
return {}
end
wesnoth.require "lua/wml/objectives.lua"
wesnoth.require "lua/wml/items.lua"
local helper = wesnoth.require "lua/helper.lua"
local location_set = wesnoth.require "lua/location_set.lua"
local wml_actions = wesnoth.wml_actions
local function trim(s)
-- use (f(a)) to get first argument
return (tostring(s):gsub("^%s*(.-)%s*$", "%1"))
end
local function split(s)
return tostring(s):gmatch("[^%s,][^,]*")
end
local function vwriter_init(cfg, default_variable)
local variable = cfg.variable or default_variable
local is_explicit_index = string.sub(variable, string.len(variable)) == "]"
local mode = cfg.mode or "always_clear"
local index = 0
if is_explicit_index then
-- explicit indexes behave always like "replace"
elseif mode == "append" then
index = wesnoth.get_variable(variable .. ".length")
elseif mode ~= "replace" then
wesnoth.set_variable(variable)
end
return {
variable = variable,
is_explicit_index = is_explicit_index,
index = index,
}
end
local function vwriter_write(self, container)
if self.is_explicit_index then
wesnoth.set_variable(self.variable, container)
else
wesnoth.set_variable(string.format("%s[%u]", self.variable, self.index), container)
end
self.index = self.index + 1
end
local function optional_side_filter(cfg, key_name, filter_name)
local key_name = key_name or "side"
local sides = cfg[key_name]
local filter_name = filter_name or "filter_side"
local filter_side = helper.get_child(cfg, filter_name)
if filter_side then
sides = wesnoth.get_sides(filter_side)
elseif sides then
local dummy_cfg = {side=sides}
sides = wesnoth.get_sides(dummy_cfg)
else
return true
end
for index,side in ipairs(sides) do
if side.controller == "human" then
return true
end
end
return false
end
local engine_message = wml_actions.message
function wml_actions.message(cfg)
local show_if = helper.get_child(cfg, "show_if")
if not show_if or wesnoth.eval_conditional(show_if) then
engine_message(cfg)
end
end
function wml_actions.chat(cfg)
local side_list = wesnoth.get_sides(cfg)
local speaker = tostring(cfg.speaker or "WML")
local message = tostring(cfg.message or
helper.wml_error "[chat] missing required message= attribute."
)
for index, side in ipairs(side_list) do
if side.controller == "human" then
wesnoth.message(speaker, message)
break
end
end
end
function wml_actions.gold(cfg)
local amount = tonumber(cfg.amount) or
helper.wml_error "[gold] missing required amount= attribute."
local sides = cfg.side
local filter_side = helper.get_child(cfg, "filter_side")
if filter_side then
wesnoth.message("warning", "[gold][filter_side] is deprecated, use only an inline SSF")
if sides then helper.wml_error("duplicate side information in [gold]") end
sides = wesnoth.get_sides(filter_side)
else
sides = wesnoth.get_sides(cfg)
end
for index, team in ipairs(sides) do
team.gold = team.gold + amount
end
end
--note: This tag can't easily (without deprecation) be extended to store an array,
--since the gold is stored in a scalar variable, not a container (there's no key).
function wml_actions.store_gold(cfg)
local team = wesnoth.get_sides(cfg)[1]
if team then wesnoth.set_variable(cfg.variable or "gold", team.gold) end
end
function wml_actions.clear_variable(cfg)
local names = cfg.name or
helper.wml_error "[clear_variable] missing required name= attribute."
for w in split(names) do
wesnoth.set_variable(trim(w))
end
end
function wml_actions.store_unit_type_ids(cfg)
local types = {}
for k,v in pairs(wesnoth.unit_types) do
table.insert(types, k)
end
table.sort(types)
types = table.concat(types, ',')
wesnoth.set_variable(cfg.variable or "unit_type_ids", types)
end
function wml_actions.store_unit_type(cfg)
local types = cfg.type or
helper.wml_error "[store_unit_type] missing required type= attribute."
local writer = vwriter_init(cfg, "unit_type")
for w in split(types) do
local unit_type = wesnoth.unit_types[w] or
helper.wml_error(string.format("Attempt to store nonexistent unit type '%s'.", w))
vwriter_write(writer, unit_type.__cfg)
end
end
function wml_actions.fire_event(cfg)
local u1 = helper.get_child(cfg, "primary_unit")
u1 = u1 and wesnoth.get_units(u1)[1]
local x1, y1 = 0, 0
if u1 then x1, y1 = u1.x, u1.y end
local u2 = helper.get_child(cfg, "secondary_unit")
u2 = u2 and wesnoth.get_units(u2)[1]
local x2, y2 = 0, 0
if u2 then x2, y2 = u2.x, u2.y end
local w1 = helper.get_child(cfg, "primary_attack")
local w2 = helper.get_child(cfg, "secondary_attack")
if w2 then w1 = w1 or {} end
wesnoth.fire_event(cfg.name, x1, y1, x2, y2, w1, w2)
end
function wml_actions.allow_recruit(cfg)
local unit_types = cfg.type or helper.wml_error("[allow_recruit] missing required type= attribute")
for index, team in ipairs(wesnoth.get_sides(cfg)) do
local v = team.recruit
for type in split(unit_types) do
table.insert(v, type)
wesnoth.add_known_unit(type)
end
team.recruit = v
end
end
function wml_actions.allow_extra_recruit(cfg)
local recruits = cfg.extra_recruit or helper.wml_error("[allow_extra_recruit] missing required extra_recruit= attribute")
for index, unit in ipairs(wesnoth.get_units(cfg)) do
local v = unit.extra_recruit
for recruit in split(recruits) do
table.insert(v, recruit)
wesnoth.add_known_unit(recruit)
end
unit.extra_recruit = v
end
end
function wml_actions.disallow_recruit(cfg)
local unit_types = cfg.type
for index, team in ipairs(wesnoth.get_sides(cfg)) do
if unit_types then
local v = team.recruit
for w in split(unit_types) do
for i, r in ipairs(v) do
if r == w then
table.remove(v, i)
break
end
end
end
team.recruit = v
else
team.recruit = nil
end
end
end
function wml_actions.disallow_extra_recruit(cfg)
local recruits = cfg.extra_recruit or helper.wml_error("[disallow_extra_recruit] missing required extra_recruit= attribute")
for index, unit in ipairs(wesnoth.get_units(cfg)) do
local v = unit.extra_recruit
for w in split(recruits) do
for i, r in ipairs(v) do
if r == w then
table.remove(v, i)
break
end
end
end
unit.extra_recruit = v
end
end
function wml_actions.set_recruit(cfg)
local recruit = cfg.recruit or helper.wml_error("[set_recruit] missing required recruit= attribute")
for index, team in ipairs(wesnoth.get_sides(cfg)) do
local v = {}
for w in split(recruit) do
table.insert(v, w)
end
team.recruit = v
end
end
function wml_actions.set_extra_recruit(cfg)
local recruits = cfg.extra_recruit or helper.wml_error("[set_extra_recruit] missing required extra_recruit= attribute")
local v = {}
for w in split(recruits) do
table.insert(v, w)
end
for index, unit in ipairs(wesnoth.get_units(cfg)) do
unit.extra_recruit = v
end
end
function wml_actions.store_map_dimensions(cfg)
local var = cfg.variable or "map_size"
local w, h, b = wesnoth.get_map_size()
wesnoth.set_variable(var .. ".width", w)
wesnoth.set_variable(var .. ".height", h)
wesnoth.set_variable(var .. ".border_size", b)
end
function wml_actions.unit_worth(cfg)
local u = wesnoth.get_units(cfg)[1] or
helper.wml_error "[unit_worth]'s filter didn't match any unit"
local ut = wesnoth.unit_types[u.type]
local hp = u.hitpoints / u.max_hitpoints
local xp = u.experience / u.max_experience
local recall_cost = unit.recall_cost
local best_adv = ut.cost
for w in split(ut.__cfg.advances_to) do
local uta = wesnoth.unit_types[w]
if uta and uta.cost > best_adv then best_adv = uta.cost end
end
wesnoth.set_variable("cost", ut.cost)
wesnoth.set_variable("next_cost", best_adv)
wesnoth.set_variable("health", math.floor(hp * 100))
wesnoth.set_variable("experience", math.floor(xp * 100))
wesnoth.set_variable("recall_cost", ut.recall_cost)
wesnoth.set_variable("unit_worth", math.floor(math.max(ut.cost * hp, best_adv * xp)))
end
function wml_actions.wml_action(cfg)
-- The new tag's name
local name = cfg.name or
helper.wml_error "[wml_action] missing required name= attribute."
local code = cfg.lua_function or
helper.wml_error "[wml_action] missing required lua_function= attribute."
local bytecode, message = load(code)
if not bytecode then
helper.wml_error("[wml_action] failed to compile Lua code: " .. message)
end
-- The lua function that is executed when the tag is called
local lua_function = bytecode() or
helper.wml_error "[wml_action] expects a Lua code returning a function."
wml_actions[name] = lua_function
end
function wml_actions.lua(cfg)
local cfg = helper.shallow_literal(cfg)
local bytecode, message = load(cfg.code or "")
if not bytecode then error("~lua:" .. message, 0) end
bytecode(helper.get_child(cfg, "args"))
end
function wml_actions.music(cfg)
wesnoth.set_music(cfg)
end
local function handle_event_commands(cfg)
-- The WML might be modifying the currently executed WML by mixing
-- [insert_tag] with [set_variables] and [clear_variable], so we
-- have to be careful not to get confused by tags vanishing during
-- the execution, hence the manual handling of [insert_tag].
local cmds = helper.shallow_literal(cfg)
for i = 1,#cmds do
local v = cmds[i]
local cmd = v[1]
local arg = v[2]
local insert_from
if cmd == "insert_tag" then
cmd = arg.name
local from = arg.variable or
helper.wml_error("[insert_tag] found with no variable= field")
arg = wesnoth.get_variable(from)
if type(arg) ~= "table" then
-- Corner case: A missing variable is replaced
-- by an empty container rather than being ignored.
arg = {}
elseif string.sub(from, -1) ~= ']' then
insert_from = from
end
arg = wesnoth.tovconfig(arg)
end
if not string.find(cmd, "^filter") then
cmd = wml_actions[cmd] or
helper.wml_error(string.format("[%s] not supported", cmd))
if insert_from then
local j = 0
repeat
cmd(arg)
j = j + 1
if j >= wesnoth.get_variable(insert_from .. ".length") then break end
arg = wesnoth.tovconfig(wesnoth.get_variable(string.format("%s[%d]", insert_from, j)))
until false
else
cmd(arg)
end
end
end
-- Apply music alterations once all the commands have been processed.
wesnoth.set_music()
end
wml_actions.command = handle_event_commands
-- since if and while are Lua keywords, we can't create functions with such names
-- instead, we store the following anonymous functions directly into
-- the table, using the [] operator, rather than by using the point syntax
wml_actions["if"] = function( cfg )
if wesnoth.eval_conditional( cfg ) then -- evaluate [if] tag
local found_something = false
for then_child in helper.child_range ( cfg, "then" ) do
handle_event_commands( then_child )
found_something = true
end
if not found_something then
if not helper.get_child( cfg, "else", nil ) then
if not helper.get_child( cfg, "elseif", nil ) then
wesnoth.message("WML warning","[if] didn't find any [then], [elseif], or [else] children. Check your {IF_VAR}!")
end
end
end
return -- stop after executing [then] tags
else
local found_something = false
for elseif_child in helper.child_range ( cfg, "elseif" ) do
if wesnoth.eval_conditional( elseif_child ) then -- we'll evaluate the [elseif] tags one by one
for then_tag in helper.child_range( elseif_child, "then" ) do
handle_event_commands( then_tag )
end
return -- stop on first matched condition
end
found_something = true
end
-- no matched condition, try the [else] tags
for else_child in helper.child_range ( cfg, "else" ) do
handle_event_commands( else_child )
found_something = true
end
if not found_something then
if not helper.get_child( cfg, "then", nil ) then
wesnoth.message("WML warning","[if] didn't find any [then], [elseif], or [else] children. Check your {IF_VAR}!")
end
end
end
end
wml_actions["while"] = function( cfg )
-- execute [do] up to 65536 times
for i = 1, 65536 do
if wesnoth.eval_conditional( cfg ) then
for do_child in helper.child_range( cfg, "do" ) do
handle_event_commands( do_child )
end
else return end
end
end
function wml_actions.switch(cfg)
local value = wesnoth.get_variable(cfg.variable)
local found = false
-- Execute all the [case]s where the value matches.
for v in helper.child_range(cfg, "case") do
local match = false
for w in split(v.value) do
if w == tostring(value) then match = true ; break end
end
if match then
handle_event_commands(v)
found = true
end
end
-- Otherwise execute [else] statements.
if not found then
for v in helper.child_range(cfg, "else") do
handle_event_commands(v)
end
end
end
function wml_actions.scroll_to(cfg)
local loc = wesnoth.get_locations( cfg )[1]
if not loc then return end
if not optional_side_filter(cfg) then return end
wesnoth.scroll_to_tile(loc[1], loc[2], cfg.check_fogged, cfg.immediate)
end
function wml_actions.scroll_to_unit(cfg)
local u = wesnoth.get_units(cfg)[1]
if not u then return end
if not optional_side_filter(cfg, "for_side", "for_side") then return end
wesnoth.scroll_to_tile(u.x, u.y, cfg.check_fogged, cfg.immediate)
end
function wml_actions.lock_view(cfg)
wesnoth.lock_view(true)
end
function wml_actions.unlock_view(cfg)
wesnoth.lock_view(false)
end
function wml_actions.select_unit(cfg)
local u = wesnoth.get_units(cfg)[1]
if not u then return end
wesnoth.select_hex(u.x, u.y, cfg.highlight, cfg.fire_event)
end
function wml_actions.unit_overlay(cfg)
local img = cfg.image or helper.wml_error( "[unit_overlay] missing required image= attribute" )
for i,u in ipairs(wesnoth.get_units(cfg)) do
local ucfg = u.__cfg
for w in split(ucfg.overlays) do
if w == img then ucfg = nil end
end
if ucfg then
ucfg.overlays = ucfg.overlays .. ',' .. img
wesnoth.put_unit(ucfg)
end
end
end
function wml_actions.remove_unit_overlay(cfg)
local img = cfg.image or helper.wml_error( "[remove_unit_overlay] missing required image= attribute" )
-- Splits the string argument on commas, excepting those commas that occur
-- within paired parentheses. The result is returned as a (non-empty) table.
-- (The table might have a single entry that is an empty string, though.)
-- Spaces around splitting commas are stripped (as in the C++ version).
-- Empty strings are not removed (unlike the C++ version).
local function parenthetical_split(str)
local t = {""}
-- To simplify some logic, end the string with paired parentheses.
local formatted = (str or "") .. ",()"
-- Isolate paired parentheses.
for prefix,paren in string.gmatch(formatted, "(.-)(%b())") do
-- Separate on commas
for comma,text in string.gmatch(prefix, "(,?)([^,]*)") do
if comma == "" then
-- We are continuing the last string found.
t[#t] = t[#t] .. text
else
-- We are starting the next string.
-- (Now that we know the last string is complete,
-- strip leading and trailing spaces from it.)
t[#t] = string.match(t[#t], "^%s*(.-)%s*$")
table.insert(t, text)
end
end
-- Add the parenthetical part to the last string found.
t[#t] = t[#t] .. paren
end
-- Remove the empty parentheses we had added to the end.
table.remove(t)
return t
end
-- Loop through all matching units.
for i,u in ipairs(wesnoth.get_units(cfg)) do
local ucfg = u.__cfg
local t = parenthetical_split(ucfg.overlays)
-- Remove the specified image from the overlays.
for i = #t,1,-1 do
if t[i] == img then table.remove(t, i) end
end
-- Reassemble the list of remaining overlays.
ucfg.overlays = table.concat(t, ',')
wesnoth.put_unit(ucfg)
end
end
function wml_actions.store_turns(cfg)
local var = cfg.variable or "turns"
wesnoth.set_variable(var, wesnoth.game_config.last_turn)
end
function wml_actions.store_unit(cfg)
local filter = helper.get_child(cfg, "filter") or
helper.wml_error "[store_unit] missing required [filter] tag"
local kill_units = cfg.kill
--cache the needed units here, since the filter might reference the to-be-cleared variable(s)
local units = wesnoth.get_units(filter)
local recall_units = wesnoth.get_recall_units(filter)
local writer = vwriter_init(cfg, "unit")
for i,u in ipairs(units) do
vwriter_write(writer, u.__cfg)
if kill_units then wesnoth.put_unit(u.x, u.y) end
end
if (not filter.x or filter.x == "recall") and (not filter.y or filter.y == "recall") then
for i,u in ipairs(recall_units) do
local ucfg = u.__cfg
ucfg.x = "recall"
ucfg.y = "recall"
vwriter_write(writer, ucfg)
if kill_units then wesnoth.extract_unit(u) end
end
end
end
function wml_actions.sound(cfg)
local name = cfg.name or helper.wml_error("[sound] missing required name= attribute")
wesnoth.play_sound(name, cfg["repeat"])
end
function wml_actions.store_locations(cfg)
-- the variable can be mentioned in a [find_in] subtag, so it
-- cannot be cleared before the locations are recovered
local locs = wesnoth.get_locations(cfg)
local writer = vwriter_init(cfg, "location")
for i, loc in ipairs(locs) do
local x, y = loc[1], loc[2]
local t = wesnoth.get_terrain(x, y)
local res = { x = x, y = y, terrain = t }
if wesnoth.get_terrain_info(t).village then
res.owner_side = wesnoth.get_village_owner(x, y) or 0
end
vwriter_write(writer, res)
end
end
function wml_actions.store_reachable_locations(cfg)
local unit_filter = helper.get_child(cfg, "filter") or
helper.wml_error "[store_reachable_locations] missing required [filter] tag"
local location_filter = helper.get_child(cfg, "filter_location")
local range = cfg.range or "movement"
local moves = cfg.moves or "current"
local variable = cfg.variable or helper.wml_error "[store_reachable_locations] missing required variable= key"
local reach_param = { viewing_side = cfg.viewing_side or 0 }
if range == "vision" then
moves = "max"
reach_param.ignore_units = true
end
local reach = location_set.create()
for i,unit in ipairs(wesnoth.get_units(unit_filter)) do
local unit_reach
if moves == "max" then
local saved_moves = unit.moves
unit.moves = unit.max_moves
unit_reach = location_set.of_pairs(wesnoth.find_reach(unit, reach_param))
unit.moves = saved_moves
else
unit_reach = location_set.of_pairs(wesnoth.find_reach(unit, reach_param))
end
if range == "vision" or range == "attack" then
unit_reach:iter(function(x, y)
reach:insert(x, y)
for u,v in helper.adjacent_tiles(x, y) do
reach:insert(u, v)
end
end)
else
reach:union(unit_reach)
end
end
if location_filter then
reach = reach:filter(function(x, y)
return wesnoth.match_location(x, y, location_filter)
end)
end
reach:to_wml_var(variable)
end
function wml_actions.hide_unit(cfg)
for i,u in ipairs(wesnoth.get_units(cfg)) do
u.hidden = true
end
wml_actions.redraw {}
end
function wml_actions.unhide_unit(cfg)
for i,u in ipairs(wesnoth.get_units(cfg)) do
u.hidden = false
end
wml_actions.redraw {}
end
--note: when using these, make sure that nothing can throw over the call to end_var_scope
local function start_var_scope(name)
local var = helper.get_variable_array(name) --containers and arrays
if #var == 0 then var = wesnoth.get_variable(name) end --scalars (and nil/empty)
wesnoth.set_variable(name)
return var
end
local function end_var_scope(name, var)
wesnoth.set_variable(name)
if type(var) == "table" then
helper.set_variable_array(name, var)
else
wesnoth.set_variable(name, var)
end
end
function wml_actions.modify_unit(cfg)
local unit_variable = "LUA_modify_unit"
local function handle_attributes(cfg, unit_path, toplevel)
for current_key, current_value in pairs(helper.shallow_parsed(cfg)) do
if type(current_value) ~= "table" and (not toplevel or current_key ~= "type") then
wesnoth.set_variable(string.format("%s.%s", unit_path, current_key), current_value)
end
end
end
local function handle_child(cfg, unit_path)
local children_handled = {}
local cfg = helper.shallow_parsed(cfg)
handle_attributes(cfg, unit_path)
for current_index, current_table in ipairs(cfg) do
local current_tag = current_table[1]
local tag_index = children_handled[current_tag] or 0
handle_child(current_table[2], string.format("%s.%s[%u]",
unit_path, current_tag, tag_index))
children_handled[current_tag] = tag_index + 1
end
end
local filter = helper.get_child(cfg, "filter") or helper.wml_error "[modify_unit] missing required [filter] tag"
local function handle_unit(unit_num)
local children_handled = {}
local unit_path = string.format("%s[%u]", unit_variable, unit_num)
local this_unit = wesnoth.get_variable(unit_path)
wesnoth.set_variable("this_unit", this_unit)
handle_attributes(cfg, unit_path, true)
for current_index, current_table in ipairs(helper.shallow_parsed(cfg)) do
local current_tag = current_table[1]
if current_tag == "filter" then
-- nothing
elseif current_tag == "object" or current_tag == "trait" then
local unit = wesnoth.get_variable(unit_path)
unit = wesnoth.create_unit(unit)
wesnoth.add_modification(unit, current_tag, current_table[2])
unit = unit.__cfg;
wesnoth.set_variable(unit_path, unit)
else
local tag_index = children_handled[current_tag] or 0
handle_child(current_table[2], string.format("%s.%s[%u]",
unit_path, current_tag, tag_index))
children_handled[current_tag] = tag_index + 1
end
end
if cfg.type then
if cfg.type ~= "" then wesnoth.set_variable(unit_path .. ".advances_to", cfg.type) end
wesnoth.set_variable(unit_path .. ".experience", wesnoth.get_variable(unit_path .. ".max_experience"))
end
wml_actions.kill({ id = this_unit.id, animate = false })
wml_actions.unstore_unit { variable = unit_path }
end
wml_actions.store_unit { {"filter", filter}, variable = unit_variable }
local max_index = wesnoth.get_variable(unit_variable .. ".length") - 1
local this_unit = start_var_scope("this_unit")
for current_unit = 0, max_index do
handle_unit(current_unit)
end
end_var_scope("this_unit", this_unit)
wesnoth.set_variable(unit_variable)
end
function wml_actions.move_unit(cfg)
local coordinate_error = "invalid coordinate in [move_unit]"
local to_x = tostring(cfg.to_x or helper.wml_error(coordinate_error))
local to_y = tostring(cfg.to_y or helper.wml_error(coordinate_error))
local fire_event = cfg.fire_event
local muf_force_scroll = cfg.force_scroll
local check_passability = cfg.check_passability or true
cfg = helper.literal(cfg)
cfg.to_x, cfg.to_y, cfg.fire_event = nil, nil, nil
local units = wesnoth.get_units(cfg)
local pattern = "[^%s,]+"
for current_unit_index, current_unit in ipairs(units) do
if not fire_event or current_unit.valid then
local xs, ys = string.gmatch(to_x, pattern), string.gmatch(to_y, pattern)
local move_string_x = current_unit.x
local move_string_y = current_unit.y
local pass_check = nil
if check_passability then pass_check = current_unit end
local x, y = xs(), ys()
local prevX, prevY = tonumber(current_unit.x), tonumber(current_unit.y)
while true do
x = tonumber(x) or helper.wml_error(coordinate_error)
y = tonumber(y) or helper.wml_error(coordinate_error)
if not (x == prevX and y == prevY) then x, y = wesnoth.find_vacant_tile(x, y, pass_check) end
if not x or not y then helper.wml_error("Could not find a suitable hex near to one of the target hexes in [move_unit].") end
move_string_x = string.format("%s,%u", move_string_x, x)
move_string_y = string.format("%s,%u", move_string_y, y)
local next_x, next_y = xs(), ys()
if not next_x and not next_y then break end
prevX, prevY = x, y
x, y = next_x, next_y
end
if current_unit.x < x then current_unit.facing = "se"
elseif current_unit.x > x then current_unit.facing = "sw"
end
wesnoth.extract_unit(current_unit)
local current_unit_cfg = current_unit.__cfg
wml_actions.move_unit_fake {
type = current_unit_cfg.type,
gender = current_unit_cfg.gender,
variation = current_unit_cfg.variation,
image_mods = current_unit.image_mods,
side = current_unit_cfg.side,
x = move_string_x,
y = move_string_y,
force_scroll = muf_force_scroll
}
local x2, y2 = current_unit.x, current_unit.y
current_unit.x, current_unit.y = x, y
wesnoth.put_unit(current_unit)
if fire_event then
wesnoth.fire_event("moveto", x, y, x2, y2)
end
end
end
end
function wml_actions.capture_village(cfg)
local side = cfg.side
local filter_side = helper.get_child(cfg, "filter_side")
local fire_event = cfg.fire_event
if side then side = tonumber(side) or helper.wml_error("invalid side in [capture_village]") end
if filter_side then
if side then helper.wml_error("duplicate side information in [capture_village]") end
side = wesnoth.get_sides(filter_side)[1]
if side then side = side.side end
end
local locs = wesnoth.get_locations(cfg)
for i, loc in ipairs(locs) do
wesnoth.set_village_owner(loc[1], loc[2], side, fire_event)
end
end
function wml_actions.terrain(cfg)
local terrain = cfg.terrain or helper.wml_error("[terrain] missing required terrain= attribute")
cfg = helper.shallow_literal(cfg)
cfg.terrain = nil
for i, loc in ipairs(wesnoth.get_locations(cfg)) do
wesnoth.set_terrain(loc[1], loc[2], terrain, cfg.layer, cfg.replace_if_failed)
end
end
function wml_actions.delay(cfg)
local delay = tonumber(cfg.time) or
helper.wml_error "[delay] missing required time= attribute."
wesnoth.delay(delay)
end
function wml_actions.floating_text(cfg)
local locs = wesnoth.get_locations(cfg)
local text = cfg.text or helper.wml_error("[floating_text] missing required text= attribute")
for i, loc in ipairs(locs) do
wesnoth.float_label(loc[1], loc[2], text)
end
end
function wml_actions.petrify(cfg)
for index, unit in ipairs(wesnoth.get_units(cfg)) do
unit.status.petrified = true
-- Extract unit and put it back to update animation (not needed for recall units)
wesnoth.extract_unit(unit)
wesnoth.put_unit(unit, unit.x, unit.y)
end
for index, unit in ipairs(wesnoth.get_recall_units(cfg)) do
unit.status.petrified = true
end
end
function wml_actions.unpetrify(cfg)
for index, unit in ipairs(wesnoth.get_units(cfg)) do
unit.status.petrified = false
-- Extract unit and put it back to update animation (not needed for recall units)
wesnoth.extract_unit(unit)
wesnoth.put_unit(unit, unit.x, unit.y)
end
for index, unit in ipairs(wesnoth.get_recall_units(cfg)) do
unit.status.petrified = false
end
end
function wml_actions.harm_unit(cfg)
local filter = helper.get_child(cfg, "filter") or helper.wml_error("[harm_unit] missing required [filter] tag")
-- we need to use shallow_literal field, to avoid raising an error if $this_unit (not yet assigned) is used
if not cfg.__shallow_literal.amount then helper.wml_error("[harm_unit] has missing required amount= attribute") end
local variable = cfg.variable -- kept out of the way to avoid problems
local _ = wesnoth.textdomain "wesnoth"
-- #textdomain wesnoth
local harmer
local function toboolean( value ) -- helper for animate fields
-- units will be animated upon leveling or killing, even
-- with special attacker and defender values
if value then return true
else return false end
end
local this_unit = start_var_scope("this_unit")
for index, unit_to_harm in ipairs(wesnoth.get_units(filter)) do
if unit_to_harm.valid then
-- block to support $this_unit
wesnoth.set_variable ( "this_unit" ) -- clearing this_unit
wesnoth.set_variable("this_unit", unit_to_harm.__cfg) -- cfg field needed
local amount = tonumber(cfg.amount)
local animate = cfg.animate -- attacker and defender are special values
local delay = cfg.delay or 500
local kill = cfg.kill
local fire_event = cfg.fire_event
local primary_attack = helper.get_child(cfg, "primary_attack")
local secondary_attack = helper.get_child(cfg, "secondary_attack")
local harmer_filter = helper.get_child(cfg, "filter_second")
local experience = cfg.experience
local resistance_multiplier = tonumber(cfg.resistance_multiplier) or 1
if harmer_filter then harmer = wesnoth.get_units(harmer_filter)[1] end
-- end of block to support $this_unit
if animate then
if animate ~= "defender" and harmer and harmer.valid then
wesnoth.scroll_to_tile(harmer.x, harmer.y, true)
wesnoth.animate_unit({ flag = "attack", hits = true, { "filter", { id = harmer.id } },
{ "primary_attack", primary_attack },
{ "secondary_attack", secondary_attack }, with_bars = true,
{ "facing", { x = unit_to_harm.x, y = unit_to_harm.y } } })
end
wesnoth.scroll_to_tile(unit_to_harm.x, unit_to_harm.y, true)
end
-- the two functions below are taken straight from the C++ engine, util.cpp and actions.cpp, with a few unuseful parts removed
-- may be moved in helper.lua in 1.11
local function round_damage( base_damage, bonus, divisor )
local rounding
if base_damage == 0 then return 0
else
if bonus < divisor or divisor == 1 then
rounding = divisor / 2 - 0
else
rounding = divisor / 2 - 1
end
return math.max( 1, math.floor( ( base_damage * bonus + rounding ) / divisor ) )
end
end
local function calculate_damage( base_damage, alignment, tod_bonus, resistance, modifier )
local damage_multiplier = 100
if alignment == "lawful" then
damage_multiplier = damage_multiplier + tod_bonus
elseif alignment == "chaotic" then
damage_multiplier = damage_multiplier - tod_bonus
elseif alignment == "liminal" then
damage_multiplier = damage_multiplier - math.abs( tod_bonus )
else -- neutral, do nothing
end
local resistance_modified = resistance * modifier
damage_multiplier = damage_multiplier * resistance_modified
local damage = round_damage( base_damage, damage_multiplier, 10000 ) -- if harmer.status.slowed, this may be 20000 ?
return damage
end
local damage = calculate_damage( amount,
( cfg.alignment or "neutral" ),
wesnoth.get_time_of_day( { unit_to_harm.x, unit_to_harm.y, true } ).lawful_bonus,
wesnoth.unit_resistance( unit_to_harm, cfg.damage_type or "dummy" ),
resistance_multiplier
)
if unit_to_harm.hitpoints <= damage then
if kill == false then damage = unit_to_harm.hitpoints - 1
else damage = unit_to_harm.hitpoints
end
end
unit_to_harm.hitpoints = unit_to_harm.hitpoints - damage
local text = string.format("%d%s", damage, "\n")
local add_tab = false
local gender = unit_to_harm.__cfg.gender
local function set_status(name, male_string, female_string, sound)
if not cfg[name] or unit_to_harm.status[name] then return end
if gender == "female" then
text = string.format("%s%s%s", text, tostring(female_string), "\n")
else
text = string.format("%s%s%s", text, tostring(male_string), "\n")
end
unit_to_harm.status[name] = true
add_tab = true
if animate and sound then -- for unhealable, that has no sound
wesnoth.play_sound (sound)
end
end
if not unit_to_harm.status.unpoisonable then
set_status("poisoned", _"poisoned", _"female^poisoned", "poison.ogg")
end
set_status("slowed", _"slowed", _"female^slowed", "slowed.wav")
set_status("petrified", _"petrified", _"female^petrified", "petrified.ogg")
set_status("unhealable", _"unhealable", _"female^unhealable")
-- Extract unit and put it back to update animation if status was changed
wesnoth.extract_unit(unit_to_harm)
wesnoth.put_unit(unit_to_harm, unit_to_harm.x, unit_to_harm.y)
if add_tab then
text = string.format("%s%s", "\t", text)
end
if animate and animate ~= "attacker" then
if harmer and harmer.valid then
wesnoth.animate_unit({ flag = "defend", hits = true, { "filter", { id = unit_to_harm.id } },
{ "primary_attack", primary_attack },
{ "secondary_attack", secondary_attack }, with_bars = true },
{ "facing", { x = harmer.x, y = harmer.y } })
else
wesnoth.animate_unit({ flag = "defend", hits = true, { "filter", { id = unit_to_harm.id } },
{ "primary_attack", primary_attack },
{ "secondary_attack", secondary_attack }, with_bars = true })
end
end
wesnoth.float_label( unit_to_harm.x, unit_to_harm.y, string.format( "<span foreground='red'>%s</span>", text ) )