-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
1716 lines (1547 loc) · 63.1 KB
/
main.lua
File metadata and controls
1716 lines (1547 loc) · 63.1 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
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
--[[
SocketBridge v3.0 — Sensor-based modular data collection framework
Key improvements over v2.x:
1. Sensors, not Collectors — each Sensor knows HOW to find entities
(EntityPartition, FindInRadius, FindByType) instead of brute-force
full-room traversal via Isaac.GetRoomEntities().
2. Dynamic throttle — combat vs idle collection rates.
3. Callback-driven triggers — MC_POST_NEW_ROOM, MC_POST_NPC_DEATH, etc.
4. Subscription negotiation — Python tells Lua what data it needs.
5. Runtime reconfiguration — CONFIGURE_SENSOR command.
6. Dual frame counters (from EID) for accurate pause handling.
Architecture:
SensorRegistry → Protocol v3.0 → Network → Python
Python → Network → CommandExecutor → Input injection / Sensor config
]]
local mod = RegisterMod("SocketBridge", 1)
local json = require("json")
-- ============================================================================
-- Configuration
-- ============================================================================
local Config = {
HOST = "127.0.0.1",
PORT = 9527,
PROTOCOL_VERSION = "3.0",
DEBUG = true, -- Enable debug logging for data flow
DEBUG_INTERVAL = 150, -- Debug output every N frames (~5 sec)
}
-- ============================================================================
-- Global State
-- ============================================================================
local State = {
connected = false,
socket = nil,
-- Dual counters (from EID pattern)
updateCount = 0, -- MC_POST_UPDATE (30 tps, respects pause)
renderCount = 0, -- MC_POST_RENDER (60 tps, ignores pause)
-- Message sequencing
messageSeq = 0,
prevFrameSent = 0,
-- Room tracking
currentRoom = -1,
roomEntered = false,
-- Subscription
subscribedSensors = {}, -- {["ENEMIES"] = true, ...}
-- Control mode
controlMode = "AUTO", -- "MANUAL" | "AUTO" | "FORCE_AI"
lastEnemyCount = 0,
wasInCombat = false,
aiActive = false,
toggleCooldown = 0,
showModeMessage = false,
modeMessageTimer = 0,
}
-- ============================================================================
-- Helpers
-- ============================================================================
local Helpers = {}
function Helpers.vectorToTable(vec)
if vec then return { x = vec.X, y = vec.Y } end
return { x = 0, y = 0 }
end
function Helpers.getPlayers()
local game = Game()
local players = {}
for i = 0, game:GetNumPlayers() - 1 do
local player = Isaac.GetPlayer(i)
if player then table.insert(players, player) end
end
return players
end
function Helpers.simpleHash(data)
if type(data) ~= "table" then return tostring(data) end
local str = ""
for k, v in pairs(data) do
if type(v) == "table" then str = str .. k .. Helpers.simpleHash(v)
else str = str .. k .. tostring(v) end
end
return str
end
-- ============================================================================
-- Network Layer (unchanged from v2.x — proven stable)
-- ============================================================================
local Network = {
retryInterval = 60,
lastRetryFrame = 0,
}
function Network.connect()
if State.connected then return true end
if State.updateCount - Network.lastRetryFrame < Network.retryInterval then
return false
end
Network.lastRetryFrame = State.updateCount
local requireOk, socketMod = pcall(function()
return require("socket.core")
end)
if not requireOk then
if State.updateCount <= 60 then
print("[SocketBridge] ERROR: require('socket.core') failed: " .. tostring(socketMod))
print("[SocketBridge] Ensure --luadebug launch option is enabled in Steam")
end
return false
end
local success, tcp = pcall(function()
local s = socketMod
local t = s.tcp()
t:settimeout(0.01)
local r = t:connect(Config.HOST, Config.PORT)
return t, r
end)
if success and tcp then
State.socket = tcp
State.connected = true
print("[SocketBridge] Connected to " .. Config.HOST .. ":" .. Config.PORT)
return true
end
if State.updateCount <= 60 then
if not success then
print("[SocketBridge] Connection attempt failed: " .. tostring(tcp))
else
print("[SocketBridge] Connection refused — Python server not running?")
end
end
return false
end
function Network.disconnect()
if State.socket then
pcall(function() State.socket:close() end)
State.socket = nil
end
State.connected = false
end
function Network.send(data)
if not State.connected then return false end
local success, err = pcall(function()
local payload = json.encode(data) .. "\n"
State.socket:send(payload)
end)
if not success then Network.disconnect(); return false end
return true
end
function Network.receive()
if not State.connected then return nil end
local success, line, err = pcall(function()
return State.socket:receive("*l")
end)
if success and line then
local ok, data = pcall(json.decode, line)
if ok then return data end
elseif err == "closed" then
Network.disconnect()
end
return nil
end
-- ============================================================================
-- Protocol v3.0
-- ============================================================================
local Protocol = {
VERSION = Config.PROTOCOL_VERSION,
MessageType = {
DATA = "DATA",
FULL = "FULL",
EVENT = "EVENT",
COMMAND = "CMD",
SUBSCRIBE_ACK = "SUBSCRIBE_ACK",
}
}
function Protocol.createDataMessage(payload, sensorNames, sensorMeta)
State.messageSeq = State.messageSeq + 1
local msg = {
version = Protocol.VERSION,
type = Protocol.MessageType.DATA,
timestamp = Isaac.GetTime(),
frame = State.updateCount,
room_index = State.currentRoom,
seq = State.messageSeq,
game_time = Isaac.GetTime(),
prev_frame = State.prevFrameSent,
sensors = sensorMeta or {},
payload = payload,
channels = sensorNames,
}
State.prevFrameSent = State.updateCount
return msg
end
function Protocol.createFullStateMessage(payload, sensorNames, sensorMeta)
State.messageSeq = State.messageSeq + 1
local msg = {
version = Protocol.VERSION,
type = Protocol.MessageType.FULL,
timestamp = Isaac.GetTime(),
frame = State.updateCount,
seq = State.messageSeq,
game_time = Isaac.GetTime(),
prev_frame = State.prevFrameSent,
sensors = sensorMeta or {},
payload = payload,
channels = sensorNames,
}
State.prevFrameSent = State.updateCount
return msg
end
function Protocol.createEventMessage(eventType, eventData)
return {
version = Protocol.VERSION,
type = Protocol.MessageType.EVENT,
timestamp = Isaac.GetTime(),
frame = State.updateCount,
event = eventType,
data = eventData,
}
end
-- ============================================================================
-- Sensor Registry (NEW — replaces CollectorRegistry)
-- ============================================================================
--
-- Sensor definition:
-- {
-- name = "ENEMIES",
-- search = {
-- strategy = "partition" | "callback" | "hybrid",
-- partitions = EntityPartition.ENEMY, -- bitmask
-- type_filter = nil, -- optional EntityType
-- radius = nil, -- nil = full room
-- sort_by_distance = true,
-- },
-- throttle = {
-- base_interval = 1, -- Frames between non-dynamic collection
-- dynamic = true, -- Switch intervals based on combat
-- combat_interval = 1,
-- idle_interval = 15,
-- },
-- extract = function(entity, player) ... end, -- Per-entity data
-- cache = {
-- strategy = "hash" | "none" | "snapshot",
-- },
-- triggers = { "MC_POST_NPC_DEATH", ... }, -- Callback-driven triggers
-- }
--
-- ============================================================================
-- Sensor Triggers (callback-driven forced collection)
-- ============================================================================
-- Sensor Triggers (callback-driven forced collection)
-- ============================================================================
local SensorTriggers = {
triggers = {}, -- {triggerName: [{sensorName, onTriggerFn}]}
}
function SensorTriggers:register(triggerName, sensorName, onTriggerFn)
if not self.triggers[triggerName] then
self.triggers[triggerName] = {}
end
table.insert(self.triggers[triggerName], {
sensorName = sensorName,
onTrigger = onTriggerFn,
})
end
function SensorTriggers:fire(triggerName, entity, forceCollectFn)
local entries = self.triggers[triggerName]
if not entries then return end
for _, entry in ipairs(entries) do
if entry.onTrigger then
entry.onTrigger(entity)
end
-- Delegate to callback to avoid circular dependency with SensorRegistry
if forceCollectFn then
forceCollectFn(entry.sensorName)
end
end
end
-- ============================================================================
-- Sensor Registry (NEW — replaces CollectorRegistry)
-- ============================================================================
local SensorRegistry = {
sensors = {},
cache = {},
changeHashes = {},
lastCollect = {},
lastCollectFrame = {},
frameCounters = {}, -- per-sensor frame counters for throttle
forcePending = {}, -- sensors force-collected this frame (always sent)
}
function SensorRegistry:register(name, def)
self.sensors[name] = {
name = name or def.name,
enabled = def.enabled ~= false,
search = def.search or { strategy = "partition" },
throttle = def.throttle or {
base_interval = 1, dynamic = false,
combat_interval = 1, idle_interval = 15,
},
extract = def.extract or function(e, p) return {} end,
cache = def.cache or {},
triggers = def.triggers or {},
}
self.cache[name] = nil
self.changeHashes[name] = nil
self.lastCollect[name] = nil
self.lastCollectFrame[name] = 0
-- Register callback triggers
if def.triggers then
for _, triggerName in ipairs(def.triggers) do
SensorTriggers:register(triggerName, name, def.onTrigger)
end
end
end
-- ── Search strategies ────────────────────────────────────────────────
function SensorRegistry:_searchEntities(sensor)
local player = Isaac.GetPlayer(0)
if not player then return {} end
local search = sensor.search
local strategy = search.strategy or "partition"
local results = {}
if strategy == "callback" then
-- Purely callback-driven, no polled search
return {}
end
if strategy == "partition" or strategy == "hybrid" then
if search.partitions and search.radius and player then
-- Use FindInRadius with EntityPartition mask (EID technique)
local radius = search.radius * 40 -- grid units → pixels
local entities = Isaac.FindInRadius(player.Position, radius, search.partitions)
for i = 1, #entities do
local e = entities[i]
if not search.type_filter or e.Type == search.type_filter then
table.insert(results, e)
end
end
elseif search.partitions and not search.radius then
-- Full room but filtered by partition
local entities = Isaac.GetRoomEntities()
for _, e in ipairs(entities) do
-- Check if entity type matches partition mask
-- (Simplified: include all for broad partitions)
if not search.type_filter or e.Type == search.type_filter then
table.insert(results, e)
end
end
elseif search.type_filter then
-- Use FindByType for specific entity type (EID technique)
local entities = Isaac.FindByType(search.type_filter, -1, -1, true, false)
for i = 1, #entities do
table.insert(results, entities[i])
end
else
-- Fallback: full room traversal
local entities = Isaac.GetRoomEntities()
for _, e in ipairs(entities) do
table.insert(results, e)
end
end
end
-- Sort by distance if requested
if search.sort_by_distance and player and #results > 0 then
local playerPos = player.Position
table.sort(results, function(a, b)
return playerPos:Distance(a.Position) < playerPos:Distance(b.Position)
end)
end
return results
end
-- ── Throttle ──────────────────────────────────────────────────────────
function SensorRegistry:_shouldCollect(sensor)
if not sensor.enabled then return false end
-- Check subscription
if next(State.subscribedSensors) and not State.subscribedSensors[sensor.name] then
return false
end
local throttle = sensor.throttle
local interval = throttle.base_interval
if throttle.dynamic then
local room = Game():GetRoom()
local inCombat = room and room:GetAliveEnemiesCount() > 0
interval = inCombat and throttle.combat_interval or throttle.idle_interval
end
if interval <= 0 then
return false -- Disabled throttle (callback-only)
end
-- Per-sensor frame counter (resets on force-collect)
local name = sensor.name
if not self.frameCounters[name] then self.frameCounters[name] = 0 end
self.frameCounters[name] = self.frameCounters[name] + 1
if self.frameCounters[name] >= interval then
self.frameCounters[name] = 0
return true
end
return false
end
-- ── Collect ───────────────────────────────────────────────────────────
function SensorRegistry:collect(name, forceCollect)
local sensor = self.sensors[name]
if not sensor then return nil, nil end
if not forceCollect and not self:_shouldCollect(sensor) then
return nil, nil
end
-- Run extract on searched entities (or custom collect function)
local success, data = pcall(function()
local player = Isaac.GetPlayer(0)
local entities = self:_searchEntities(sensor)
local results = {}
for _, entity in ipairs(entities) do
local entry = sensor.extract(entity, player)
if entry then
table.insert(results, entry)
end
end
return results
end)
if not success then
return nil, nil
end
if data == nil or (type(data) == "table" and #data == 0 and next(data) == nil) then
return nil, nil
end
-- Hash-based change detection
if not forceCollect and sensor.cache.strategy == "hash" then
local newHash = Helpers.simpleHash(data)
if self.changeHashes[name] == newHash then
return nil, nil -- Unchanged
end
self.changeHashes[name] = newHash
end
self.cache[name] = data
self.lastCollectFrame[name] = State.updateCount
local meta = {
collect_frame = State.updateCount,
collect_time = Isaac.GetTime(),
interval = sensor.throttle.dynamic and "dynamic" or "fixed",
stale_frames = 0,
entity_count = #data,
hash = self.changeHashes[name] or "",
}
SensorRegistry.lastCollect[name] = meta
return data, meta
end
function SensorRegistry:collectAll()
local results = {}
local collectedNames = {}
local collectedMeta = {}
for name, _ in pairs(self.sensors) do
local data, meta = self:collect(name, false)
if data ~= nil then
results[name] = data
table.insert(collectedNames, name)
collectedMeta[name] = meta
end
end
-- Include force-pending sensors (force-collected this frame)
-- These have cached data but throttle may have blocked them
for name, _ in pairs(self.forcePending) do
local cached = self.cache[name]
if cached ~= nil and results[name] == nil then
results[name] = cached
table.insert(collectedNames, name)
collectedMeta[name] = self.lastCollect[name] or {
collect_frame = State.updateCount,
collect_time = Isaac.GetTime(),
interval = "forced",
stale_frames = 0,
entity_count = (type(cached) == "table" and #cached) or 0,
hash = self.changeHashes[name] or "",
}
end
end
-- Clear force-pending for next frame
self.forcePending = {}
return results, collectedNames, collectedMeta
end
function SensorRegistry:forceCollectAll()
local results = {}
local names = {}
local meta = {}
for name, _ in pairs(self.sensors) do
local data, m = self:collect(name, true)
if data ~= nil then
results[name] = data
table.insert(names, name)
meta[name] = m
end
end
return results, names, meta
end
function SensorRegistry:getCached(name)
return self.cache[name]
end
function SensorRegistry:getConfig(name)
local sensor = self.sensors[name]
if not sensor then return nil end
return {
name = sensor.name,
enabled = sensor.enabled,
throttle = sensor.throttle,
search = sensor.search,
}
end
function SensorRegistry:getAllConfigs()
local configs = {}
for name, _ in pairs(self.sensors) do
configs[name] = self:getConfig(name)
end
return configs
end
function SensorRegistry:setEnabled(name, enabled)
if self.sensors[name] then
self.sensors[name].enabled = enabled
end
end
function SensorRegistry:setThrottle(name, throttleConfig)
local sensor = self.sensors[name]
if sensor then
for k, v in pairs(throttleConfig) do
sensor.throttle[k] = v
end
end
end
-- ============================================================================
-- Sensor Definitions (all 12 sensors ported from v2.x + enhanced)
-- ============================================================================
-- 1. PLAYER_POSITION (HIGH frequency, single entity — no search needed)
SensorRegistry:register("PLAYER_POSITION", {
name = "PLAYER_POSITION",
search = { strategy = "callback" }, -- Direct API, no entity search
throttle = { base_interval = 1, dynamic = false },
cache = { strategy = "hash" },
extract = function() -- Override collect behavior per-sensor
-- This sensor uses a custom collect function, defined below
end,
})
-- 2. PLAYER_STATS (LOW frequency)
SensorRegistry:register("PLAYER_STATS", {
name = "PLAYER_STATS",
search = { strategy = "callback" },
throttle = { base_interval = 30, dynamic = false },
cache = { strategy = "hash" },
})
-- 3. PLAYER_HEALTH (LOW frequency)
SensorRegistry:register("PLAYER_HEALTH", {
name = "PLAYER_HEALTH",
search = { strategy = "callback" },
throttle = { base_interval = 30, dynamic = false },
cache = { strategy = "hash" },
})
-- 4. PLAYER_INVENTORY (RARE frequency)
SensorRegistry:register("PLAYER_INVENTORY", {
name = "PLAYER_INVENTORY",
search = { strategy = "callback" },
throttle = { base_interval = 90, dynamic = false },
cache = { strategy = "hash" },
})
-- 5. ENEMIES (HIGH in combat, LOW idle)
SensorRegistry:register("ENEMIES", {
name = "ENEMIES",
search = {
strategy = "partition",
partitions = EntityPartition.ENEMY,
sort_by_distance = true,
},
throttle = {
base_interval = 1, dynamic = true,
combat_interval = 1, idle_interval = 15,
},
cache = { strategy = "hash" },
triggers = { "MC_POST_NPC_DEATH", "MC_POST_NEW_ROOM" },
extract = function(entity, player)
if not entity:IsActiveEnemy(false) or not entity:IsVulnerableEnemy() then
return nil
end
local npc = entity:ToNPC()
local targetPos = { x = 0, y = 0 }
if npc then
local target = npc:GetPlayerTarget()
if target then targetPos = Helpers.vectorToTable(target.Position) end
end
return {
id = entity.Index,
type = entity.Type, variant = entity.Variant, subtype = entity.SubType,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
hp = entity.HitPoints, max_hp = entity.MaxHitPoints,
is_boss = entity:IsBoss(),
is_champion = npc and npc:IsChampion() or false,
state = npc and npc.State or 0,
state_frame = npc and npc.StateFrame or 0,
projectile_cooldown = npc and npc.ProjectileCooldown or 0,
projectile_delay = npc and npc.ProjectileDelay or 0,
collision_radius = entity.Size,
distance = player and player.Position:Distance(entity.Position) or 0,
target_pos = targetPos,
v1 = npc and Helpers.vectorToTable(npc.V1) or { x = 0, y = 0 },
v2 = npc and Helpers.vectorToTable(npc.V2) or { x = 0, y = 0 },
}
end,
})
-- 6. PROJECTILES (HIGH in combat, LOW idle)
SensorRegistry:register("PROJECTILES", {
name = "PROJECTILES",
search = {
strategy = "partition",
partitions = EntityPartition.BULLET + EntityPartition.EFFECT,
},
throttle = {
base_interval = 1, dynamic = true,
combat_interval = 1, idle_interval = 15,
},
cache = { strategy = "hash" },
triggers = { "MC_POST_NEW_ROOM" },
extract = function(entity, player)
-- We override this with a custom collect — see custom sensor handlers below
end,
})
-- 7. ROOM_INFO (on room change + LOW)
SensorRegistry:register("ROOM_INFO", {
name = "ROOM_INFO",
search = { strategy = "callback" },
throttle = { base_interval = 15, dynamic = false },
cache = { strategy = "hash" },
triggers = { "MC_POST_NEW_ROOM" },
})
-- 8. ROOM_LAYOUT (on room change)
SensorRegistry:register("ROOM_LAYOUT", {
name = "ROOM_LAYOUT",
search = { strategy = "callback" },
throttle = { base_interval = -1, dynamic = false }, -- Callback-only
cache = { strategy = "snapshot" },
triggers = { "MC_POST_NEW_ROOM" },
})
-- 9. BOMBS (LOW frequency)
SensorRegistry:register("BOMBS", {
name = "BOMBS",
search = {
strategy = "partition",
type_filter = EntityType.ENTITY_BOMB,
},
throttle = { base_interval = 15, dynamic = false },
cache = { strategy = "hash" },
extract = function(entity, player)
if entity.Type ~= EntityType.ENTITY_BOMB then return nil end
local bomb = entity:ToBomb()
local dist = player and player.Position:Distance(entity.Position) or 0
local BOMB_VARIANTS = {
[0]="NORMAL",[1]="BIG",[2]="DECOY",[3]="TROLL",[4]="MEGA_TROLL",
[5]="POISON",[6]="BIG_POISON",[7]="SAD",[8]="HOT",[9]="BUTT",
[10]="MR_MEGA",[11]="BOBBY",[12]="GLITTER",[13]="THROWABLE",
[14]="SMALL",[15]="BRIMSTONE",[16]="BLOODY_SAD",[17]="GIGA",
[18]="GOLDEN_TROLL",[19]="ROCKET",[20]="GIGA_ROCKET",
}
return {
id = entity.Index, type = entity.Type,
variant = entity.Variant,
variant_name = BOMB_VARIANTS[entity.Variant] or ("UNKNOWN_" .. entity.Variant),
sub_type = entity.SubType,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
explosion_radius = bomb and bomb.ExplosionRadius or 0,
timer = bomb and bomb.Timer or 0,
distance = dist,
}
end,
})
-- 10. INTERACTABLES (LOW frequency)
SensorRegistry:register("INTERACTABLES", {
name = "INTERACTABLES",
search = {
strategy = "partition",
type_filter = 6, -- EntityType 6 = interactable entities
},
throttle = { base_interval = 15, dynamic = false },
cache = { strategy = "hash" },
extract = function(entity, player)
if entity.Type ~= 6 then return nil end
local npc = entity:ToNPC()
local dist = player and player.Position:Distance(entity.Position) or 0
local INTERACTABLE_VARIANTS = {
[1]="SLOT_MACHINE",[2]="BLOOD_DONATION",[3]="FORTUNE_TELLING",
[4]="BEGGAR",[5]="DEVIL_BEGGAR",[6]="SHELL_GAME",
[7]="KEY_MASTER",[8]="DONATION_MACHINE",[9]="BOMB_BUM",
[10]="RESTOCK_MACHINE",[11]="GREED_MACHINE",[12]="MOMS_DRESSING_TABLE",
[13]="BATTERY_BUM",[14]="ISAAC_SECRET",[15]="HELL_GAME",
[16]="CRANE_GAME",[17]="CONFESSIONAL",[18]="ROTTEN_BEGGAR",
[19]="REVIVE_MACHINE",
}
local target = npc and npc:GetPlayerTarget()
return {
id = entity.Index, type = entity.Type,
variant = entity.Variant,
variant_name = INTERACTABLE_VARIANTS[entity.Variant] or ("UNKNOWN_" .. entity.Variant),
sub_type = entity.SubType,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
state = npc and npc.State or 0,
state_frame = npc and npc.StateFrame or 0,
target_pos = target and Helpers.vectorToTable(target.Position) or { x = 0, y = 0 },
distance = dist,
}
end,
})
-- 11. PICKUPS (LOW frequency + callback on pickup init)
SensorRegistry:register("PICKUPS", {
name = "PICKUPS",
search = {
strategy = "partition",
partitions = EntityPartition.PICKUP,
},
throttle = { base_interval = 15, dynamic = false },
cache = { strategy = "hash" },
triggers = { "MC_POST_PICKUP_INIT", "MC_POST_NEW_ROOM" },
extract = function(entity, player)
if entity.Type ~= EntityType.ENTITY_PICKUP then return nil end
local pickup = entity:ToPickup()
return {
id = entity.Index,
variant = entity.Variant,
sub_type = entity.SubType,
pos = Helpers.vectorToTable(entity.Position),
price = pickup and pickup.Price or 0,
shop_item_id = pickup and pickup.ShopItemId or -1,
wait = pickup and pickup.Wait or 0,
}
end,
})
-- 12. FIRE_HAZARDS (LOW frequency)
SensorRegistry:register("FIRE_HAZARDS", {
name = "FIRE_HAZARDS",
search = { strategy = "hybrid" },
throttle = { base_interval = 15, dynamic = false },
cache = { strategy = "hash" },
extract = function(entity, player)
local dist = player and player.Position:Distance(entity.Position) or 0
-- Handle fire effects (bomb fire, candle flame)
local DANGEROUS_FIRE = { [51] = true, [52] = true }
local FIREPLACE_TYPES = {
[0]="NORMAL",[1]="RED",[2]="BLUE",[3]="PURPLE",[4]="WHITE",
[10]="MOVABLE",[11]="COAL",[12]="MOVABLE_BLUE",[13]="MOVABLE_PURPLE",
}
if entity.Type == EntityType.ENTITY_EFFECT then
if DANGEROUS_FIRE[entity.Variant] then
return {
id = entity.Index, type = "EFFECT", variant = entity.Variant,
pos = Helpers.vectorToTable(entity.Position),
collision_radius = entity.Size > 0 and entity.Size or 20,
distance = dist,
}
end
elseif entity.Type == 33 then -- ENTITY_FIREPLACE
local variant = entity.Variant
local isExtinguished = entity.State == 1000
local isShooting = false
local npc = entity:ToNPC()
if npc and (variant == 1 or variant == 3) then
isShooting = (npc.State == 8)
end
return {
id = entity.Index, type = "FIREPLACE",
fireplace_type = FIREPLACE_TYPES[variant] or ("UNKNOWN_" .. variant),
variant = variant, sub_variant = entity.SubType,
pos = Helpers.vectorToTable(entity.Position),
hp = entity.HitPoints, max_hp = entity.MaxHitPoints,
state = entity.State, is_extinguished = isExtinguished,
collision_radius = entity.Size > 0 and entity.Size or 25,
distance = dist, is_shooting = isShooting,
sprite_scale = entity.SpriteScale.X,
}
end
return nil
end,
})
-- ═══════════════════════════════════════════════════════════════════════
-- Custom sensor collect functions (override search-based collection)
-- These sensors don't use entity search — they query the API directly.
-- ═══════════════════════════════════════════════════════════════════════
local CustomCollectors = {}
function CustomCollectors.PLAYER_POSITION()
local players = Helpers.getPlayers()
local data = {}
for i, player in ipairs(players) do
data[i] = {
pos = Helpers.vectorToTable(player.Position),
vel = Helpers.vectorToTable(player.Velocity),
move_dir = player:GetMovementDirection(),
fire_dir = player:GetFireDirection(),
head_dir = player:GetHeadDirection(),
aim_dir = Helpers.vectorToTable(player:GetAimDirection()),
}
end
return data
end
function CustomCollectors.PLAYER_STATS()
local players = Helpers.getPlayers()
local data = {}
for i, player in ipairs(players) do
data[i] = {
player_type = player:GetPlayerType(),
damage = player.Damage, speed = player.MoveSpeed,
tears = player.MaxFireDelay,
range = player.TearRange, tear_range = player.TearRange,
shot_speed = player.ShotSpeed, luck = player.Luck,
tear_height = player.TearHeight,
tear_falling_speed = player.TearFallingSpeed,
can_fly = player.CanFly, size = player.Size,
sprite_scale = player.SpriteScale.X,
}
end
return data
end
function CustomCollectors.PLAYER_HEALTH()
local players = Helpers.getPlayers()
local data = {}
for i, player in ipairs(players) do
data[i] = {
red_hearts = player:GetHearts(), max_hearts = player:GetMaxHearts(),
soul_hearts = player:GetSoulHearts(), black_hearts = player:GetBlackHearts(),
bone_hearts = player:GetBoneHearts(), golden_hearts = player:GetGoldenHearts(),
eternal_hearts = player:GetEternalHearts(), rotten_hearts = player:GetRottenHearts(),
broken_hearts = player:GetBrokenHearts(), extra_lives = player:GetExtraLives(),
}
end
return data
end
function CustomCollectors.PLAYER_INVENTORY()
local players = Helpers.getPlayers()
local data = {}
for i, player in ipairs(players) do
local playerData = {
coins = player:GetNumCoins(), bombs = player:GetNumBombs(),
keys = player:GetNumKeys(),
trinket_0 = player:GetTrinket(0), trinket_1 = player:GetTrinket(1),
card_0 = player:GetCard(0), pill_0 = player:GetPill(0),
collectible_count = player:GetCollectibleCount(),
}
-- Collectibles
local items = {}
if playerData.collectible_count > 0 then
for itemId = 1, 733 do
if player:HasCollectible(itemId, true) then
local count = player:GetCollectibleNum(itemId, true)
if count > 0 then items[tostring(itemId)] = count end
end
end
end
playerData.collectibles = items
-- Active items
local activeSlots = {}
for slot = 0, 3 do
local activeItem = player:GetActiveItem(slot)
if activeItem > 0 then
activeSlots[tostring(slot)] = {
item = activeItem,
charge = player:GetActiveCharge(slot),
max_charge = player:GetActiveMaxCharge(slot),
battery_charge = player:GetBatteryCharge(slot),
}
end
end
playerData.active_items = activeSlots
data[i] = playerData
end
return data
end
function CustomCollectors.PROJECTILES()
local player = Isaac.GetPlayer(0)
if not player then return { enemy_projectiles = {}, player_tears = {}, lasers = {} } end
local data = { enemy_projectiles = {}, player_tears = {}, lasers = {} }
for _, entity in ipairs(Isaac.GetRoomEntities()) do
if entity.Type == EntityType.ENTITY_PROJECTILE then
local proj = entity:ToProjectile()
table.insert(data.enemy_projectiles, {
id = entity.Index,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
variant = entity.Variant, collision_radius = entity.Size,
height = proj and proj.Height or 0,
falling_speed = proj and proj.FallingSpeed or 0,
falling_accel = proj and proj.FallingAccel or 0,
})
elseif entity.Type == EntityType.ENTITY_TEAR then
local tear = entity:ToTear()
local tearData = {
id = entity.Index,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
variant = entity.Variant, collision_radius = entity.Size,
height = tear and tear.Height or 0,
scale = tear and tear.Scale or 1,
}
if entity.SpawnerType == EntityType.ENTITY_PLAYER then
table.insert(data.player_tears, tearData)
else
table.insert(data.enemy_projectiles, tearData)
end
elseif entity.Type == EntityType.ENTITY_LASER then
local laser = entity:ToLaser()
if laser then
table.insert(data.lasers, {
id = entity.Index,
pos = Helpers.vectorToTable(entity.Position),
angle = laser.Angle, max_distance = laser.MaxDistance,
is_enemy = entity:IsEnemy(),
})
end
end
end
return data
end
function CustomCollectors.ROOM_INFO()
local room = Game():GetRoom()
local level = Game():GetLevel()
if not room then return nil end
local tl = room:GetTopLeftPos()
local br = room:GetBottomRightPos()