Move to new sign-based threat refuge system

This commit is contained in:
Tanner committed 2026-11-10 23:10:37 +00:00
1 parent 038fc503f0
commit 586772cb3b
6 files changed
+418 -195

No files matched your search

+19
View File
@@ -24,6 +24,7 @@ from munch import Munch
from mosfet import commands
from mosfet import game
from mosfet.jobs import check_threats
from mosfet import job
from mosfet import path
from mosfet import print_help
@@ -39,6 +40,7 @@ for module in [
blocks,
commands,
game,
check_threats,
items,
job,
mcdata,
@@ -607,6 +609,7 @@ def refresh_runtime(global_state, reload_managers=False):
"""Rebind reloadable runtime adapters without touching the connection."""
g = global_state
connection = g.get('connection')
previous_threat_monitor = g.get('threat_monitor')
_remove_instance_listeners(connection, g.get('chat'))
_remove_instance_listeners(connection, g.get('game'))
@@ -643,6 +646,22 @@ def refresh_runtime(global_state, reload_managers=False):
replacement_state = getattr(g.job, state_name, None)
if replacement_state is not None:
g.job.state = replacement_state
from mosfet.jobs.check_threats import ThreatMonitor
threat_monitor = ThreatMonitor(g)
if previous_threat_monitor is not None:
monitor_state = getattr(
previous_threat_monitor.state, '__name__', 'watching')
for attribute in (
'next_scan_at', 'retry_at', 'safe_since', 'safety',
'safe_sign', 'threats', 'resume_job_name',
'job_suspended'):
if hasattr(previous_threat_monitor, attribute):
setattr(threat_monitor, attribute,
getattr(previous_threat_monitor, attribute))
threat_monitor.state = getattr(
threat_monitor, monitor_state, threat_monitor.watching)
g.threat_monitor = threat_monitor
g.commands = commands.Commands(g)
if not reload_managers:
g.mcdata = DataManager()
-10
View File
@@ -17,7 +17,6 @@ from mosfet.info import mobs
from mosfet.jobs import (
cache_items,
check_threats,
clear_leaves,
eat_food,
fill_blocks,
@@ -36,7 +35,6 @@ from mosfet.jobs import (
for module in [
cache_items,
check_threats,
clear_leaves,
eat_food,
fill_blocks,
@@ -71,7 +69,6 @@ class LegacyJobStates:
self.grab_sapling_states = grab_sapling.GrabSaplingStates(self.g)
self.grab_sand_states = grab_sand.GrabSandStates(self.g)
self.fill_blocks_states = fill_blocks.FillBlocksStates(self.g)
self.check_threats_states = check_threats.CheckThreatsStates(self.g)
self.gather_wart_states = gather_wart.GatherWartStates(self.g)
self.gather_crop_states = gather_crop.GatherCropStates(self.g)
self.eat_food_states = eat_food.EatFoodStates(self.g)
@@ -105,7 +102,6 @@ class LegacyJobStates:
def farm_sand(self):
machines = [
self.grab_supplies_states,
self.check_threats_states,
self.gather_sand_states,
self.grab_sand_states,
self.cache_items_states,
@@ -216,7 +212,6 @@ class LegacyJobStates:
def loiter(self):
machines = [
self.check_threats_states,
self.sleep_with_bed_states,
self.eat_food_states,
]
@@ -285,8 +280,6 @@ class JobStates(LegacyJobStates):
self.sleep_with_bed_states = sleep_with_bed.SleepWithBedStates(
global_state)
self.eat_food_states = eat_food.EatFoodStates(global_state)
self.check_threats_states = check_threats.CheckThreatsStates(
global_state)
self.active_machine = None
self.state = self.idle
@@ -373,9 +366,6 @@ class JobStates(LegacyJobStates):
self.sleep_with_bed_states.state = self.sleep_with_bed_states.idle
self.sleep_with_bed_states.force_new_bed = False
self.eat_food_states.state = self.eat_food_states.idle
self.check_threats_states.state = self.check_threats_states.idle
self.check_threats_states.safety = None
self.check_threats_states.external_safety = False
self.gather_crop_states.active_section_anchor = None
self.gather_crop_states.completed_crops = 0
self.active_machine = None
+70 -160
View File
@@ -1,19 +1,6 @@
import re
import time
import importlib
import random
from itertools import count
from math import floor
from minecraft.networking.types import BlockFace
from mosfet.protocol.managers import ChunkNotLoadedException
from mosfet import utils
from mosfet import path
from mosfet.info import blocks
from mosfet.info import items
from mosfet.info import mcdata
from mosfet.info import mobs
class ThreatMonitor:
@@ -59,32 +46,54 @@ class ThreatMonitor:
print('[threat] queued job change until the area is safe', flush=True)
self._stop_job()
def _nearby_hostiles(self, position, distance):
finder = getattr(self.g.world, 'find_monsters', None)
if callable(finder):
return finder(position, distance)
return self.g.world.find_threats(position, distance)
@staticmethod
def _describe_threat(threat):
mob_name = mobs.MOB_NAMES.get(
threat.get('type'), 'unknown type {}'.format(threat.get('type')))
return '{}#{} at ({:.1f}, {:.1f}, {:.1f})'.format(
mob_name, threat.get('entity_id', '?'),
threat.get('x', 0.0), threat.get('y', 0.0),
threat.get('z', 0.0))
def _find_safety(self):
world = self.g.world
position = utils.pint(self.g.pos)
self.safety = None
self.g.path = []
safety_blocks = world.find_blocks_indexed(
position, {blocks.EMERALD_BLOCK}, self.SAFETY_SEARCH_DISTANCE)
for block in safety_blocks:
spot = utils.padd(block, path.BLOCK_ABOVE)
if world.find_threats(spot, self.CLEAR_DISTANCE):
continue
navpath = world.path_to_place(position, spot)
if navpath is not None:
self.safety = spot
self.g.path = navpath
print('[threat] evacuating to safety marker', spot, flush=True)
return True
find_signs = getattr(world, 'find_safety_signs', None)
find_openings = getattr(world, 'find_safety_openings', None)
if callable(find_signs) and callable(find_openings):
signs = find_signs(
position, self.g.get('name', ''), self.SAFETY_SEARCH_DISTANCE)
for sign in signs:
for spot in find_openings(sign):
navpath = world.path_to_place(position, spot)
if navpath is None:
continue
self.safety = tuple(spot)
self.safe_sign = sign
self.g.path = navpath
print('[threat] evacuating to signed refuge',
self.safety, flush=True)
return True
# Preserve a conservative fallback when no addressed refuge sign is
# nearby or reachable. These fallback spots are not trusted shelters.
for spot in world.find_bed_areas(
position, self.CLEAR_DISTANCE * 2):
if world.find_threats(spot, self.CLEAR_DISTANCE):
if self._nearby_hostiles(spot, self.CLEAR_DISTANCE):
continue
navpath = world.path_to_place(position, spot)
if navpath is not None:
self.safety = spot
self.safety = tuple(spot)
self.safe_sign = None
self.g.path = navpath
print('[threat] fleeing to clear area', spot, flush=True)
return True
@@ -94,18 +103,24 @@ class ThreatMonitor:
return False
def watching(self):
job = self.g.get('job')
if job is None or job.state == job.idle:
self.next_scan_at = 0.0
return
now = time.monotonic()
if now < self.next_scan_at:
return
self.next_scan_at = now + self.CHECK_INTERVAL
threats = self.g.world.find_threats(
threats = self._nearby_hostiles(
utils.pint(self.g.pos), self.THREAT_DISTANCE)
if not threats:
return
self.threats = threats
descriptions = '; '.join(self._describe_threat(threat)
for threat in threats)
print('[threat] detected {} nearby hostile(s); pausing job: {}'.format(
len(threats), threats), flush=True)
len(threats), descriptions), flush=True)
self._suspend_job()
self.g.look_at = None
self.safe_since = None
@@ -117,19 +132,10 @@ class ThreatMonitor:
now = time.monotonic()
if now >= self.next_scan_at:
self.next_scan_at = now + self.CHECK_INTERVAL
position = utils.pint(self.g.pos)
threats = self.g.world.find_threats(
position, self.THREAT_DISTANCE)
threats = self._nearby_hostiles(
utils.pint(self.g.pos), self.THREAT_DISTANCE)
if threats:
self.threats = threats
if (self.safety is not None and
self.g.world.find_threats(
self.safety, self.CLEAR_DISTANCE)):
print('[threat] planned refuge is no longer clear; '
'choosing another', flush=True)
self.safety = None
self.g.path = []
self._find_safety()
if self.safety is not None and utils.pint(self.g.pos) == self.safety:
self.g.path = []
@@ -140,8 +146,16 @@ class ThreatMonitor:
flush=True)
return
if not self.g.path and now >= self.retry_at:
if self.safety is None and now >= self.retry_at:
self._find_safety()
elif (self.safety is not None and not self.g.path and
now >= self.retry_at):
navpath = self.g.world.path_to_place(
utils.pint(self.g.pos), self.safety)
if navpath is not None:
self.g.path = navpath
else:
self.retry_at = now + self.CHECK_INTERVAL
def waiting(self):
self._capture_job_change()
@@ -149,16 +163,20 @@ class ThreatMonitor:
if now < self.next_scan_at:
return
self.next_scan_at = now + self.CHECK_INTERVAL
threats = self.g.world.find_threats(
utils.pint(self.g.pos), self.CLEAR_DISTANCE)
if threats:
print('[threat] hostile still within safety radius; moving again',
flush=True)
self.threats = threats
self.safe_since = None
self.safety = None
position = utils.pint(self.g.pos)
if position != self.safety:
# If knockback or a correction moved us off the refuge, return to
# the same sign instead of searching for another one.
self.state = self.evacuating
self._find_safety()
self.retry_at = 0.0
return
# Signs explicitly designate trusted refuges. Keep monitoring nearby
# threats so work only resumes after the patrol has moved away, but
# never ray-test or blacklist the sign's refuge.
if self._nearby_hostiles(position, self.CLEAR_DISTANCE):
self.safe_since = None
return
if self.safe_since is None:
@@ -178,6 +196,7 @@ class ThreatMonitor:
self.resume_job_name = None
self.job_suspended = False
self.safety = None
self.safe_sign = None
self.safe_since = None
self.next_scan_at = time.monotonic() + self.CHECK_INTERVAL
self.state = self.watching
@@ -196,118 +215,9 @@ class ThreatMonitor:
self.retry_at = 0.0
self.safe_since = None
self.safety = None
self.safe_sign = None
self.threats = []
self.resume_job_name = None
self.job_suspended = False
self.suspending_job = False
class CheckThreatsStates:
THREAT_DISTANCE = 20
CLEAR_DISTANCE = 30
CHECK_INTERVAL = 2.0
def idle(self):
return None
def init(self):
self.state = self.find_threats
print('Checking for threats')
def find_threats(self):
w = self.g.world
p = utils.pint(self.g.pos)
threats = w.find_threats(p, self.THREAT_DISTANCE)
if threats:
print('Found', len(threats), 'threats, seeking safety:')
print(threats)
self.threats = threats
self.state = self.find_safety
else:
self.wait_time = self.CHECK_INTERVAL
self.state = self.wait
def find_safety(self):
w = self.g.world
p = utils.pint(self.g.pos)
safety_blocks = w.find_blocks_indexed(
p, [blocks.EMERALD_BLOCK], self.THREAT_DISTANCE * 4)
for block in safety_blocks:
spot = utils.padd(block, path.BLOCK_ABOVE)
if w.find_threats(spot, self.CLEAR_DISTANCE):
continue
navpath = w.path_to_place(p, spot)
if navpath is not None:
self.safety = spot
self.external_safety = True
self.g.path = navpath
self.state = self.going_to_safety
print('Going to emerald safety point', self.safety)
return
# No configured emerald safe point was reachable. Retreat to a clear,
# supported location that the modern navigator can actually reach.
for spot in w.find_bed_areas(p, self.CLEAR_DISTANCE * 2):
if w.find_threats(spot, self.CLEAR_DISTANCE):
continue
navpath = w.path_to_place(p, spot)
if navpath is not None:
self.safety = spot
self.external_safety = False
self.g.path = navpath
self.state = self.going_to_safety
print('Fleeing to clear area', self.safety)
return
print('No reachable safe area found')
self.wait_time = self.CHECK_INTERVAL
self.state = self.wait
def going_to_safety(self):
if utils.pint(self.g.pos) == self.safety:
if self.external_safety:
print('At emerald safety point, waiting for server move')
self.state = self.wait_for_move
else:
print('At clear retreat spot')
self.wait_time = 3
self.state = self.wait
def wait_for_move(self):
# wait for the server to move the bot when it's safe
# ie. a piston + daylight sensor
if utils.pint(self.g.pos) != self.safety:
print('Moved, resuming job')
self.state = self.wait
self.wait_time = 3
def wait(self):
# wait to land, etc
if self.wait_time > 0:
self.wait_time -= utils.TICK
else:
self.state = self.cleanup
def cleanup(self):
self.g.look_at = None
self.state = self.done
def done(self):
# never gets ran, placeholder
return None
def __init__(self, global_state):
self.g = global_state
self.state = self.idle
self.safety = None
self.wait_time = 0
self.threats = []
self.external_safety = False
def run(self):
self.state()
+58 -1
View File
@@ -159,6 +159,64 @@ class World:
center, directive['position']))
return result
def find_safety_signs(self, center, bot_name, distance=80):
"""Find nearby signs addressed to this bot that mark safe refuges."""
bot_name = str(bot_name).casefold()
group_name = (bot_name[:-1] if len(bot_name) > 1 and
bot_name[-1] in '123' else None)
addresses = {bot_name}
if group_name:
addresses.add(group_name)
result = []
for sign in self.find_signs(center, distance):
lines = [line.strip() for line in sign['lines'] if line.strip()]
if not lines:
continue
tokens = re.findall(r'[a-z0-9_]+', ' '.join(lines).casefold())
if (len(tokens) < 2 or tokens[0] not in addresses or
not {'safety', 'refuge'}.intersection(tokens[1:])):
continue
state_id = self.block_at(*sign['position'])
result.append({
'position': tuple(sign['position']),
'side': sign['side'],
'lines': sign['lines'],
'normal': self._sign_text_normal(sign, state_id),
})
result.sort(key=lambda sign: utils.phyp(center, sign['position']))
return result
def find_safety_openings(self, sign, radius=3):
"""Return standable positions near a trusted refuge sign, front first."""
sign_pos = tuple(sign['position'])
normal_x, _, normal_z = sign['normal']
if abs(normal_x) >= abs(normal_z):
front = (1 if normal_x >= 0 else -1, 0, 0)
else:
front = (0, 0, 1 if normal_z >= 0 else -1)
directions = (
front,
(front[2], 0, -front[0]),
(-front[2], 0, front[0]),
(-front[0], 0, -front[2]),
)
candidates = []
for direction_rank, direction in enumerate(directions):
for distance in range(1, radius + 1):
for dy in (0, -1, 1):
if utils.hypot(distance, dy) > radius:
continue
offset = tuple(component * distance
for component in direction)
position = utils.padd(
sign_pos, (offset[0], dy, offset[2]))
if self._cache_opening_standable(position):
candidates.append((
direction_rank, distance, abs(dy), position))
candidates.sort()
return [candidate[3] for candidate in candidates]
def find_throw_openings(self, sign, center, radius=3):
"""Find standable, visible throw positions within radius of a sign."""
sign_pos = tuple(sign['position'])
@@ -366,7 +424,6 @@ class World:
support_machines = (
'grab_supplies_states', 'sleep_with_bed_states',
'eat_food_states', 'cache_items_states',
'check_threats_states',
)
if any(machine is getattr(job, name, None)
for name in support_machines):