-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcover.lua
More file actions
507 lines (448 loc) · 18.3 KB
/
cover.lua
File metadata and controls
507 lines (448 loc) · 18.3 KB
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
-- cover.lua
-- Tactical cover system for adventure mode.
-- Detects cover from adjacent solid tiles using the Opposite Pairs Algorithm,
-- announces cover changes when the player has a weapon in hand, and reduces
-- the hit probability of incoming projectiles when the player is in cover.
local eventful = require('plugins.eventful')
local repeatUtil = require('repeat-util')
local GCfg = _G.__GunConfig
if not GCfg or not GCfg._loaded then
dfhack.printerr("[cover] FATAL: __GunConfig not set — bw_autoload must run first")
return
end
local CALLBACK_ID = "cover"
local S = _G.__cover or {}
_G.__cover = S
if S.enabled == nil then S.enabled = false end
if S.DEBUG == nil then S.DEBUG = false end
if S.last_cover_level == nil then S.last_cover_level = "none" end
if S.processed_projectiles == nil then S.processed_projectiles = {} end
if S.last_enemy_cover == nil then S.last_enemy_cover = "none" end
if S.last_aim_target_id == nil then S.last_aim_target_id = -1 end
---------------------------------------------------------------------------
-- CONFIG
---------------------------------------------------------------------------
local POLL_INTERVAL = 3 -- ticks between cover polls
-- Miss chance per directional cover level
local COVER_MISS_CHANCE = {
none = 0.00,
light = 0.25,
medium = 0.40,
heavy = 0.55,
}
-- Numeric rank for global vs directional flanking comparison
local COVER_RANK = { none=0, light=1, medium=2, heavy=3, full=4 }
local COVER_BY_RANK = { [0]="none", [1]="light", [2]="medium", [3]="heavy" }
-- Weapons that reduce the effective cover level of their target (weapon_id → pen degrees).
local COVER_PEN_WEAPONS = GCfg.COVER_PEN_WEAPONS
-- Announcement colors: color index, bright flag
local COVER_COLORS = {
light = { color = 14, bright = true }, -- YELLOW
medium = { color = 10, bright = true }, -- LGREEN
heavy = { color = 10, bright = true }, -- LCYAN
full = { color = 10, bright = true }, -- WHITE
none = { color = 4, bright = false }, -- LGRAY
}
-- Enemy cover colors: indicate how hard the target is to hit
local ENEMY_COVER_COLORS = {
none = { color = 10, bright = true }, -- LGREEN — clear shot
light = { color = 14, bright = true }, -- YELLOW
medium = { color = 12, bright = true }, -- LRED
heavy = { color = 4, bright = true }, -- RED
}
-- Opposite Pairs: 4 axis-aligned pairs of (dx, dy) directions.
-- A pair contributes to cover only when exactly one direction is solid.
local OPPOSITE_PAIRS = {
{ {0,-1}, {0,1} }, -- N / S
{ {1,-1}, {-1,1} }, -- NE / SW
{ {1,0}, {-1,0} }, -- E / W
{ {-1,-1}, {1,1} }, -- NW / SE
}
-- All 8 adjacent directions for directional cover half-plane scan
local ALL_8_DIRS = {
{0,-1},{0,1},{1,0},{-1,0},
{1,-1},{-1,1},{-1,-1},{1,1}
}
---------------------------------------------------------------------------
-- INVENTORY MODE SHIM (same pattern as ammo.lua)
---------------------------------------------------------------------------
local WEAPON_MODE
local ok_new, inv_role = pcall(function() return df.inv_item_role_type end)
local ok_old, t_mode = pcall(function() return df.unit_inventory_item.T_mode end)
if ok_new and inv_role then
WEAPON_MODE = inv_role.Weapon
elseif ok_old and t_mode then
WEAPON_MODE = t_mode.Weapon
else
print("[cover] WARNING: Cannot resolve inventory Weapon mode enum!")
WEAPON_MODE = 2 -- best-guess fallback
end
---------------------------------------------------------------------------
-- HELPERS
---------------------------------------------------------------------------
local function is_adventure_mode()
local ok, result = pcall(function()
return df.global.gamemode == df.game_mode.ADVENTURE
end)
return ok and result
end
local function is_player_unit(unit)
local adv = dfhack.world.getAdventurer()
return adv ~= nil and adv.id == unit.id
end
-- Returns true if (x,y,z) is a solid cover-providing tile: Wall, Fortification,
-- or Trunk. Invalid/unloaded positions are treated as open (returns false).
local function is_solid_tile(x, y, z)
local ok, result = pcall(function()
if not dfhack.maps.isValidTilePos(x, y, z) then return false end
local tt = dfhack.maps.getTileType(x, y, z)
if not tt then return false end
local shape = df.tiletype.attrs[tt].shape
if not shape then return false end
local basic = df.tiletype_shape.attrs[shape].basic_shape
return basic == df.tiletype_shape_basic.Wall
or basic == df.tiletype_shape_basic.Fortification
or basic == df.tiletype_shape_basic.Trunk
end)
return ok and result
end
-- Returns true if the unit is prone (on the ground, voluntary or otherwise).
local function is_prone(unit)
local ok, result = pcall(function() return unit.flags1.on_ground end)
return ok and result
end
-- Returns true if the player has a weapon item in Weapon mode.
local function has_weapon_ready(unit)
local ok, result = pcall(function()
for _, inv in ipairs(unit.inventory) do
if inv.mode == WEAPON_MODE
and inv.item:getType() == df.item_type.WEAPON then
return true
end
end
return false
end)
return ok and result
end
-- Raw cover score (0–4) for any map position: counts asymmetric OPPOSITE_PAIRS.
-- Exposed as _G.__cover.score_at for use by maneuver.lua cover-seeking movement.
local function cover_score_at(x, y, z)
local count = 0
for _, pair in ipairs(OPPOSITE_PAIRS) do
local d1, d2 = pair[1], pair[2]
if is_solid_tile(x+d1[1], y+d1[2], z) ~= is_solid_tile(x+d2[1], y+d2[2], z) then
count = count + 1
end
end
return count
end
S.score_at = cover_score_at
-- Opposite Pairs Algorithm: count asymmetric pairs (one solid, one open).
-- Returns "none" | "light" | "medium" | "heavy" | "full"
local function compute_cover(unit)
local x, y, z = unit.pos.x, unit.pos.y, unit.pos.z
local pairs_count = cover_score_at(x, y, z)
if is_prone(unit) then pairs_count = pairs_count + 1 end
pairs_count = math.min(pairs_count, 4)
if pairs_count == 0 then return "none"
elseif pairs_count == 1 then return "light"
elseif pairs_count == 2 then return "medium"
elseif pairs_count == 3 then return "heavy"
else return "full"
end
end
-- Directional cover: count solid tiles in the attacker's half-plane.
-- dir = {nx, ny} normalized vector from player toward attacker.
-- Returns "none" | "light" | "medium" | "heavy" (fortified not used here)
local function compute_directional_cover(unit, dir)
local x, y, z = unit.pos.x, unit.pos.y, unit.pos.z
local count = 0
for _, d in ipairs(ALL_8_DIRS) do
-- A tile is in the attacker's half-plane when its direction dot-products
-- positive with the player→attacker vector (i.e. it's between them).
if d[1] * dir[1] + d[2] * dir[2] > 0 then
if is_solid_tile(x + d[1], y + d[2], z) then
count = count + 1
end
end
end
if is_prone(unit) then count = count + 1 end
if count == 0 then return "none"
elseif count == 1 then return "light"
elseif count == 2 then return "medium"
else return "heavy"
end
end
-- Resolve bow_id to the firer unit's readable name, falling back to
-- profession/title for unnamed units (creatures with no generated name).
local function get_attacker_name(bow_id)
if not bow_id or bow_id < 0 then return "Unknown" end
for _, unit in ipairs(df.global.world.units.active) do
if dfhack.units.isActive(unit) and not dfhack.units.isDead(unit) then
for _, inv_item in ipairs(unit.inventory) do
if inv_item.item.id == bow_id then
local ok, name = pcall(dfhack.units.getReadableName, unit)
if ok and name and name ~= "" then return name end
local ok2, prof = pcall(dfhack.units.getProfessionName, unit)
if ok2 and prof and prof ~= "" then return prof end
return "Unknown"
end
end
end
end
return "Unknown"
end
-- True if this projectile is targeting the player (spec_target or position match).
local function projectile_targets_player(proj, player)
local ok1, spec = pcall(function() return proj.spec_target_unit end)
if ok1 and spec == player.id then return true end
local ok2, hit = pcall(function()
return proj.target_pos.x == player.pos.x
and proj.target_pos.y == player.pos.y
and proj.target_pos.z == player.pos.z
end)
return ok2 and hit
end
-- Returns the first active unit standing at (x, y, z), or nil.
local function find_unit_at(x, y, z)
for _, unit in ipairs(df.global.world.units.active) do
if dfhack.units.isActive(unit) and not dfhack.units.isDead(unit)
and unit.pos.x == x and unit.pos.y == y and unit.pos.z == z then
return unit
end
end
return nil
end
-- Returns the unit targeted by a pending ShootRangedWeapon action, or nil.
local function get_aim_target(player)
local target = nil
pcall(function()
for i = 0, #player.actions - 1 do
local act = player.actions[i]
if act.type == df.unit_action_type.ShootRangedWeapon then
local d = act.data.shootrangedweapon
target = find_unit_at(d.target_lx, d.target_ly, d.target_lz)
return
end
end
end)
return target
end
---------------------------------------------------------------------------
-- COVER POLL (adventure mode announcements)
---------------------------------------------------------------------------
local function poll_cover()
if not S.enabled then return end
if not is_adventure_mode() then return end
if not dfhack.isMapLoaded() then return end
local player = dfhack.world.getAdventurer()
if not player then return end
-- Periodic cleanup: remove entries for projectiles that no longer exist
pcall(function()
local proj_list = df.global.world.projectiles
if not proj_list then return end
local live = {}
for _, proj in ipairs(proj_list.all) do
live[proj.id] = true
end
for pid in pairs(S.processed_projectiles) do
if not live[pid] then
S.processed_projectiles[pid] = nil
end
end
end)
-- Announcements only when a weapon is wielded
if not has_weapon_ready(player) then return end
local current = compute_cover(player)
if current == S.last_cover_level then return end
-- Announce the change
if current == "none" then
local c = COVER_COLORS.none
dfhack.gui.showAnnouncement("Out of cover!", c.color, c.bright)
else
local label = current:sub(1,1):upper() .. current:sub(2) .. " cover!"
local c = COVER_COLORS[current]
dfhack.gui.showAnnouncement(label, c.color, c.bright)
end
S.last_cover_level = current
-- Enemy cover: check cover of the currently aimed-at target
local aim_target = get_aim_target(player)
if aim_target then
local px, py = player.pos.x, player.pos.y
local tx, ty = aim_target.pos.x, aim_target.pos.y
local ddx, ddy = px - tx, py - ty -- target → player
local dist = math.sqrt(ddx * ddx + ddy * ddy)
if dist >= 0.5 then
local dir = { ddx / dist, ddy / dist }
local enemy_cover = compute_directional_cover(aim_target, dir)
if enemy_cover ~= S.last_enemy_cover or aim_target.id ~= S.last_aim_target_id then
local c = ENEMY_COVER_COLORS[enemy_cover]
if enemy_cover == "none" then
dfhack.gui.showAnnouncement("Clear shot!", c.color, c.bright)
else
local label = enemy_cover:sub(1,1):upper() .. enemy_cover:sub(2)
dfhack.gui.showAnnouncement("Target: " .. label .. " cover", c.color, c.bright)
end
S.last_enemy_cover = enemy_cover
S.last_aim_target_id = aim_target.id
end
end
else
-- No longer aiming; reset so next aim always announces
S.last_enemy_cover = "none"
S.last_aim_target_id = -1
end
end
---------------------------------------------------------------------------
-- PROJECTILE HOOK
---------------------------------------------------------------------------
local function on_proj_move(proj)
if not S.enabled then return end
if not is_adventure_mode() then return end
-- Only process each projectile once (first movement tick)
if S.processed_projectiles[proj.id] then return end
local player = dfhack.world.getAdventurer()
if not player then return end
if not projectile_targets_player(proj, player) then return end
S.processed_projectiles[proj.id] = true
-- Compute normalized vector from player toward attacker (origin)
local ox, oy = proj.cur_pos.x, proj.cur_pos.y
pcall(function()
ox = proj.origin_pos.x
oy = proj.origin_pos.y
end)
local px, py = player.pos.x, player.pos.y
local ddx, ddy = ox - px, oy - py -- player → attacker
local dist = math.sqrt(ddx * ddx + ddy * ddy)
if dist < 0.5 then return end -- point-blank; skip cover check
local dir = { ddx / dist, ddy / dist }
local dir_level = compute_directional_cover(player, dir)
-- Cover penetration: sniper rifles (and any weapon with cover_pen) reduce the
-- effective cover level by that many degrees before the miss roll.
local eff_level = dir_level
pcall(function()
local weapon = df.item.find(proj.bow_id)
if not weapon or weapon:getType() ~= df.item_type.WEAPON then return end
local ok, wid = pcall(function()
return dfhack.items.getSubtypeDef(df.item_type.WEAPON, weapon:getSubtype()).id
end)
local pen = ok and wid and COVER_PEN_WEAPONS[wid]
if pen and pen > 0 then
local rank = math.max(0, (COVER_RANK[dir_level] or 0) - pen)
eff_level = COVER_BY_RANK[rank] or "none"
if S.DEBUG and eff_level ~= dir_level then
dfhack.print(("[cover] cover_pen %d: %s -> %s (%s)\n"):format(
pen, dir_level, eff_level, wid))
end
end
end)
local miss_chance = COVER_MISS_CHANCE[eff_level] or 0
if miss_chance > 0 and math.random() < miss_chance then
-- Redirect projectile 10 tiles past the player along its speed vector
local sx, sy = 0, 0
pcall(function()
sx = proj.speed_x
sy = proj.speed_y
end)
local smag = math.sqrt(sx * sx + sy * sy)
local ex, ey
if smag >= 0.5 then
-- Extend along current flight direction
ex = px + math.floor(sx / smag * 10 + 0.5)
ey = py + math.floor(sy / smag * 10 + 0.5)
else
-- Fallback: extend away from attacker
ex = px - math.floor(ddx / dist * 10 + 0.5)
ey = py - math.floor(ddy / dist * 10 + 0.5)
end
pcall(function()
proj.target_pos.x = ex
proj.target_pos.y = ey
proj.spec_target_unit = -1
proj.target_bp = -1
end)
if S.DEBUG then
print(("[cover] Miss! dir=%s chance=%.0f%% -> (%d,%d)"):format(
dir_level, miss_chance * 100, ex, ey))
end
end
-- Flanking check: is global cover better than cover from this attacker?
local global_level = compute_cover(player)
local global_rank = COVER_RANK[global_level] or 0
local dir_rank = COVER_RANK[dir_level] or 0
if global_rank > dir_rank and global_rank > 0 then
local bow_id = -1
pcall(function() bow_id = proj.bow_id end)
local name = get_attacker_name(bow_id)
local msg
if dir_level == "none" then
msg = name .. " flanked! Cover reduced to no cover!"
else
msg = name .. " flanked! Cover reduced to " .. dir_level .. " cover!"
end
dfhack.gui.showAnnouncement(msg, 4, true) -- COLOR_RED
end
end
---------------------------------------------------------------------------
-- ENABLE / DISABLE / STATUS
---------------------------------------------------------------------------
local function enable()
if S.enabled then
print("[cover] Already enabled")
return
end
eventful.onProjItemCheckMovement[CALLBACK_ID] = on_proj_move
repeatUtil.scheduleEvery(CALLBACK_ID, POLL_INTERVAL, "ticks", poll_cover)
S.enabled = true
S.last_cover_level = "none"
S.last_enemy_cover = "none"
S.last_aim_target_id = -1
S.processed_projectiles = {}
print("[cover] Enabled")
end
local function disable()
if not S.enabled then
print("[cover] Already disabled")
return
end
eventful.onProjItemCheckMovement[CALLBACK_ID] = nil
repeatUtil.cancel(CALLBACK_ID)
S.enabled = false
S.last_cover_level = "none"
S.last_enemy_cover = "none"
S.last_aim_target_id = -1
S.processed_projectiles = {}
print("[cover] Disabled")
S.DEBUG = false
end
local function status()
local proj_count = 0
for _ in pairs(S.processed_projectiles) do proj_count = proj_count + 1 end
print(("[cover] Status: %s | Debug: %s | Tracked projectiles: %d"):format(
S.enabled and "ENABLED" or "DISABLED",
S.DEBUG and "ON" or "OFF",
proj_count))
if is_adventure_mode() and dfhack.isMapLoaded() then
local player = dfhack.world.getAdventurer()
if player then
print(("[cover] Current cover: %s"):format(compute_cover(player)))
end
end
end
---------------------------------------------------------------------------
-- ARGUMENT PARSING
---------------------------------------------------------------------------
local args = { ... }
local command = args[1] or "enable"
if command == "enable" then
enable()
elseif command == "disable" then
disable()
elseif command == "status" then
status()
elseif command == "debug" then
S.DEBUG = not S.DEBUG
print(("[cover] Debug: %s"):format(S.DEBUG and "ON" or "OFF"))
else
print("[cover] Usage: cover [enable|disable|status|debug]")
end