Add signed general cache destinations

This commit is contained in:
Tanner committed 2026-11-14 23:12:50 +00:00
1 parent 11c1bad0c4
commit 86fbf911a5
7 files changed
+305 -114

No files matched your search

+32 -8
View File
@@ -49,8 +49,8 @@ the next manual start, rather than triggering an automatic reconnect.
The 26.3 client now handles AuthMe, chat commands, chunk/world-state caching,
modern block/item/entity data, entity tracking, inventory/component sync,
path-following movement (`1goto x y z`), inventory draining (`1drain`),
normal/trapped-chest caching (`1cache`, also run by crop farming at the
inventory threshold), bed sleeping (`1sleep`, or `1sleep new` to place a bed;
sign-directed item-specific and general chest caching (`1cache`, also run by
crop farming at the inventory threshold), bed sleeping (`1sleep`, or `1sleep new` to place a bed;
also run by crop farming at night), food use (`1eat`, also run as needed by
crop farming), the crop harvest/replant loop (`1farm crops`), tree/log farming
(`1farm logs`, with `1farm wood` as an alias), and death-screen respawning
@@ -78,8 +78,10 @@ address is optional.
Put one or more item-category labels on a sign next to a chest. A standing
sign can be placed on top of the chest, or a wall sign can be attached to a
horizontal side. If no chest is in those positions, the nearest chest(s)
within two blocks are associated. Double chests are treated as one container.
horizontal side. If both a side-adjacent chest and a chest directly below
the sign are nearby, the side chest takes priority. Otherwise, if no chest is
in those positions, the nearest chest(s) within two blocks are associated.
Double chests are treated as one container.
Each recognized line adds items to the chest's accepted categories:
- `Seeds` — `beetroot_seeds`, `melon_seeds`, `pumpkin_seeds`,
@@ -87,6 +89,8 @@ Each recognized line adds items to the chest's accepted categories:
- `Wheat` — wheat only; wheat seeds are not included.
- `Logs` — every log item in the current 26.3 data, including stripped logs,
wood, stems, and hyphae.
- `Oak Logs` (and labels such as `Spruce Logs`) — that tree's log family,
including stripped and wood forms, plus stems/hyphae where applicable.
- `Saplings` — all tree saplings and propagules in the current 26.3 data,
including the mangrove propagule.
@@ -100,6 +104,23 @@ Logs
Saplings
```
### General cache chests
To make a normal chest a general-purpose cache destination, put `cache` after
the bot or group name on its sign:
```
mosfet cache
mosfet1 cache
```
The sign can be on top of or attached to the chest, using the same chest
association rules as item labels. General cache chests within 105 blocks are
used only after all matching item-specific labeled chests, even if a general
chest is closer. Unmarked trapped chests are no longer discovered or used for
caching. If no signed destination is usable, Mosfet can still place a normal
chest from its inventory.
### Supply chests
Put the sign on top of or attach it to the supply chest, then address it with
@@ -122,12 +143,15 @@ sign:
```
mosfet1 throw Logs
mosfet throw Wheat Seeds
mosfet1 throw minecraft:oak_log
mosfet1 throw oak_log
mosfet1 throw Oak Logs
```
The first form uses a category label (so `Logs` matches the whole log family);
the last form uses an exact item name. Multiword item names are joined with
underscores for lookup. The bot searches for a reachable, standable position
Category labels can target groups (`Logs`) or one tree family (`Oak Logs`). An
exact item name such as `oak_log` needs no `minecraft:` prefix; prefixed names
are also accepted. The exact item form matches only that item, while `Oak Logs` includes stripped
and wood forms for that species. Other multiword exact item names can be written
with spaces or underscores. The bot searches for a reachable, standable position
within three blocks with line of sight to the sign, then drops whole stacks of
the requested items. Use this only where dropping those items is intended.
+37 -20
View File
@@ -1,28 +1,45 @@
# Mosfet Minecraft Bot
# How to Cache Items
## How to Cache Items
Caching normally starts when the bot has at least 27 occupied inventory slots.
Jobs can run cache passes automatically; `1cache` requests a pass directly.
![a single trapped chest with three normal double chests under it](media/cache_items.png)
## Destination priority
Mosfet will automatically dump items into the closest [trapped
chest](https://minecraft.fandom.com/wiki/Trapped_Chest#Crafting) once his
inventory gets full enough. Normally this is when the number of used inventory
slots is >= 27.
A cache pass handles destinations in this order:
If Mosfet can't find a trapped chest nearby, he will place down a normal chest
if he has one in his inventory. Then he will store the items in it.
1. **Throw signs** — addressed `throw` directives drop matching inventory stacks
near their signs.
2. **Item-specific chests** — signs labeled `Seeds`, `Wheat`, `Logs`, `Saplings`,
or a tree family such as `Oak Logs` direct matching items to nearby chests.
3. **General cache chests** — a normal chest marked with a bot-addressed `cache`
sign accepts any otherwise-cacheable items. These are lower priority than
all item-specific chests, regardless of distance.
4. **Placed chest** — if no signed chest destination is usable, the bot places a
normal chest from its inventory when it has one.
Mosfet won't cache items related to his current job. For example, if he's
farming wood, he will keep axes, beds, chests, and food.
Unmarked trapped chests are no longer searched for or used as cache destinations.
### Advanced Details
See the [Signs section in the main README](../README.md#signs) for sign syntax,
addresses, category contents, and examples. General cache signs look like:
The global `g.minimum_cache_slots` in `bot.py` controls the minimum amount of
used slots needed to trigger item caching.
```
mosfet cache
```
In `jobs.py`, each job calls `items.set_wanted()` and `items.set_needed()` to
control which items Mosfet shouldn't cache. No items in the "needed" list will
be cached and all items in the "wanted" list—except for one stack of each—will
be cached. The "needed" list is meant for essentials like tools, food, and beds,
while the "wanted" list is for stuff that's good to have a stack of like seeds
and saplings.
or, for one bot only:
```
mosfet1 cache
```
The bot searches for signed cache chests within 105 blocks. Chest attachment,
side-over-top priority, double-chest handling, and bot-group addressing follow
the same rules as other signs described in the README.
## Items kept
Items in the current job's `NEEDED_ITEMS` set are kept in general cache passes.
For `WANTED_ITEMS`, the bot keeps one stack of each type and may cache extras.
Item-specific chests only accept their labeled item IDs, while general cache
chests accept all otherwise-cacheable items. The normal cache threshold is
controlled by `g.minimum_cache_slots` in `mosfet.py` (default 27).
+12
View File
@@ -47,6 +47,17 @@ AXE_IDS = get_set(AXES)
FOOD_IDS = get_set(FOOD)
SAPLING_IDS = get_set(SAPLINGS)
LOG_IDS = get_set(LOGS)
_LOG_FAMILY_ITEM_IDS = {}
for _name in LOGS:
_unstripped_name = _name.removeprefix('stripped_')
for _suffix in ('_log', '_wood', '_stem', '_hyphae'):
if _unstripped_name.endswith(_suffix):
_family_name = _unstripped_name[:-len(_suffix)] + ' log'
_family_items = get_set({_name})
if _family_items:
_LOG_FAMILY_ITEM_IDS.setdefault(
_family_name, set()).update(_family_items)
break
ITEM_NAMES = {item['protocol_id']: name.removeprefix('minecraft:')
for name, item in ITEMS.items()}
@@ -92,6 +103,7 @@ _LABEL_ITEM_IDS = {
'wheat': {WHEAT_ID},
'log': LOG_IDS,
'sapling': SAPLING_IDS,
**_LOG_FAMILY_ITEM_IDS,
}
+64 -63
View File
@@ -12,7 +12,6 @@ from mosfet.protocol.managers import ChunkNotLoadedException
from mosfet import utils
from mosfet import path
from mosfet.jobs.work_boundary import WorkBoundaryReturnMixin
from mosfet.info import blocks
from mosfet.info import items
from mosfet.info import mobs
@@ -42,15 +41,7 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
position)
self._processed_chest_open_events.intersection_update(current_events)
def _chest_positions(self, chest):
finder = getattr(self.g.world, '_double_chest_positions', None)
if finder:
positions = finder(tuple(chest))
if positions:
return tuple(tuple(position) for position in positions)
return (tuple(chest),)
def _has_compatible_labeled_chest_near(self, bed, distance=16):
def _has_compatible_cache_chest_near(self, bed, distance=16):
world = self.g.get('world')
if world is None:
return False
@@ -69,6 +60,13 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
slot in keep_slots):
continue
return True
for chest in world.find_cache_chests(
bed, self.g.get('name', ''), distance):
positions = chest.get('positions') or (chest['position'],)
if min(utils.phyp(bed, position) for position in positions) > distance:
continue
if self._has_transferable_item(items.ITEM_NAMES):
return True
return False
def _find_throw_signs(self):
@@ -152,7 +150,7 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
print('No reachable throw opening for sign', sign['position'])
self.throw_sign = None
self.state = self.choose_trapped_chest
self.state = self.choose_cache_chest
def going_to_throw_sign(self):
if utils.pint(self.g.pos) == self.opening:
@@ -234,7 +232,7 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
'minimum', self.g.get('minimum_cache_slots', 27))
post_sleep_bed = self.g.pop('post_sleep_cache_bed', None)
if (not has_override and post_sleep_bed is not None and
self._has_compatible_labeled_chest_near(post_sleep_bed)):
self._has_compatible_cache_chest_near(post_sleep_bed)):
minimum = ceil(minimum / 2)
print('Lowering cache threshold after sleep near a compatible chest:',
minimum)
@@ -242,13 +240,13 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
if num_stacks == 0:
self.state = self.cleanup
elif num_stacks >= minimum:
self.state = self.find_trapped_chests
self.state = self.find_cache_targets
else:
print('Aborting caching, not full')
self.state = self.cleanup
def find_trapped_chests(self):
print('Finding labeled and trapped chests...')
def find_cache_targets(self):
print('Finding item-specific and general cache chests...')
w = self.g.world
p = utils.pint(self.g.pos)
@@ -256,10 +254,11 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
self.checked_throw_signs = set()
self.labeled_chests = w.find_labeled_chests(p, 105)
self.checked_labeled_chests = set()
self.trapped_chests = w.find_blocks_indexed(p, blocks.TRAPPED_CHEST_IDS)
print('Found {} labeled chests; found {} trapped chests: {}'.format(
len(self.labeled_chests), len(self.trapped_chests),
self.trapped_chests))
self.cache_chests = w.find_cache_chests(
p, self.g.get('name', ''), 105)
self.checked_cache_chests = set()
print('Found {} item-specific chests and {} general cache chests'.format(
len(self.labeled_chests), len(self.cache_chests)))
self.state = self.choose_throw_sign
def _opening_in_bad_region(self, world, opening):
@@ -276,8 +275,8 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
return True
return False
def choose_trapped_chest(self):
print('Choosing a labeled or trapped chest...')
def choose_cache_chest(self):
print('Choosing an item-specific or general cache chest...')
self.bad_openings = set()
w = self.g.world
p = utils.pint(self.g.pos)
@@ -310,61 +309,62 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
self.open_interaction = opening
self.g.path = navpath
self.g.look_at = None
self.state = self.going_to_trapped_chest
self.state = self.going_to_cache_chest
return
self.bad_openings.add(opening_position)
print('No path to labeled chest', self.area)
while (self.trapped_chests and
self._chest_positions(self.trapped_chests[0]) in
self.useless_chests):
self.trapped_chests.pop(0)
if not len(self.trapped_chests):
self.is_labeled_container = False
self.container_item_ids = None
if self.transferred_to_labeled_chest:
print('Already cached items in labeled chests; skipping new chest')
self.state = self.cleanup
return
print('No labeled or trapped chests')
self.state = self.select_chest
return
# General cache chests are a fallback, after all matching item-specific
# chests have been checked.
self.is_labeled_container = False
self.container_item_ids = None
chest = self.trapped_chests[0]
self.area = chest
self.current_container_key = self._chest_positions(chest)
for opening in w.find_cache_openings(chest, p):
opening_position = tuple(opening['position'])
if self._opening_in_bad_region(w, opening_position):
for container in self.cache_chests:
key = tuple(tuple(position) for position in
(container.get('positions') or
(container['position'],)))
if (key in self.checked_cache_chests or
key in self.useless_chests):
continue
self.checked_cache_chests.add(key)
if not self._has_transferable_item(items.ITEM_NAMES):
continue
navpath = w.path_to_place(p, opening_position)
if (navpath and
self._accept_cache_trip(p, opening_position, navpath)):
print('navpath to trapped chest:', navpath)
self.opening = opening_position
self.open_interaction = opening
self.g.path = navpath
self.g.look_at = None
self.state = self.going_to_trapped_chest
return
self.bad_openings.add(opening_position)
self.trapped_chests.pop(0)
time.sleep(0.1)
chest = container['position']
self.area = chest
self.current_container_key = key
for opening in w.find_cache_openings(chest, p):
opening_position = tuple(opening['position'])
if self._opening_in_bad_region(w, opening_position):
continue
navpath = w.path_to_place(p, opening_position)
if (navpath and
self._accept_cache_trip(p, opening_position, navpath)):
print('Going to general cache chest:', chest)
self.opening = opening_position
self.open_interaction = opening
self.g.path = navpath
self.g.look_at = None
self.state = self.going_to_cache_chest
return
self.bad_openings.add(opening_position)
print('No path to general cache chest:', chest)
def going_to_trapped_chest(self):
if self.transferred_to_labeled_chest:
print('Already cached items in item-specific chests; skipping new chest')
self.state = self.cleanup
return
print('No item-specific or general cache chests')
self.state = self.select_chest
def going_to_cache_chest(self):
if utils.pint(self.g.pos) == self.opening:
self.g.look_at = self.open_interaction['look_at']
self.wait_time = 0.5
self.state = self.turn_to_trapped_chest
self.state = self.turn_to_cache_chest
else:
self.g.look_at = None
def turn_to_trapped_chest(self):
def turn_to_cache_chest(self):
self.g.look_at = self.open_interaction['look_at']
self.wait_time -= utils.TICK
if self.wait_time <= 0:
@@ -629,7 +629,7 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
if self.is_labeled_container:
self.is_labeled_container = False
self.container_item_ids = None
self.state = self.choose_trapped_chest
self.state = self.choose_cache_chest
else:
self.state = self.cleanup
@@ -660,6 +660,8 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
self.labeled_chests = []
self.checked_labeled_chests = set()
self.cache_chests = []
self.checked_cache_chests = set()
self.useless_chests = set()
self._processed_chest_open_events = {
self._chest_event_key(event)
@@ -672,7 +674,6 @@ class CacheItemsStates(WorkBoundaryReturnMixin):
self.area = None
self.opening = None
self.open_interaction = None
self.trapped_chests = []
self.bad_areas = []
self.wait_time = 0
self.throw_signs = []
+64 -22
View File
@@ -140,7 +140,8 @@ class World:
tokens[1] != 'throw'):
continue
item_name = '_'.join(tokens[2:])
item_ids = items.storage_item_ids_for_label(item_name)
item_label = ' '.join(tokens[2:])
item_ids = items.storage_item_ids_for_label(item_label)
if not item_ids:
item_ids = items.get_set({item_name})
if not item_ids:
@@ -272,13 +273,35 @@ class World:
return tuple(sorted((tuple(chest), partner)))
return (tuple(chest),)
def _chests_associated_with_sign(self, sign):
sign_pos = tuple(sign['position'])
side_offsets = (
(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1),
)
top_offsets = ((0, 0, 0), (0, -1, 0))
adjacent = {
utils.padd(sign_pos, offset)
for offset in side_offsets
if self.block_at(*utils.padd(sign_pos, offset)) in blocks.CHEST_IDS
}
if not adjacent:
adjacent = {
utils.padd(sign_pos, offset)
for offset in top_offsets
if self.block_at(*utils.padd(sign_pos, offset)) in blocks.CHEST_IDS
}
if not adjacent:
nearby = self.find_blocks_indexed(
sign_pos, blocks.CHEST_IDS, 2)
if nearby:
nearest = min(utils.phyp(sign_pos, chest) for chest in nearby)
adjacent = {chest for chest in nearby
if utils.phyp(sign_pos, chest) == nearest}
return adjacent
def find_labeled_chests(self, center, distance=105):
"""Find single/double chests assigned item categories by nearby signs."""
grouped = {}
sign_offsets = (
(0, 0, 0), (0, -1, 0),
(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1),
)
for sign in self.find_signs(center, distance):
categories = set()
labels = set()
@@ -290,22 +313,9 @@ class World:
if not categories:
continue
sign_pos = sign['position']
adjacent = {
utils.padd(sign_pos, offset)
for offset in sign_offsets
if self.block_at(*utils.padd(sign_pos, offset)) in blocks.CHEST_IDS
}
if not adjacent:
nearby = self.find_blocks_indexed(
sign_pos, blocks.CHEST_IDS, 2)
if nearby:
nearest = min(utils.phyp(sign_pos, chest)
for chest in nearby)
adjacent = {chest for chest in nearby
if utils.phyp(sign_pos, chest) == nearest}
for chest in adjacent:
# Side-mounted signs take priority over signs on top when chests
# occupy both positions beside the sign.
for chest in self._chests_associated_with_sign(sign):
positions = self._double_chest_positions(chest)
record = grouped.setdefault(positions, {
'position': tuple(chest),
@@ -316,7 +326,39 @@ class World:
})
record['item_ids'].update(categories)
record['labels'].update(labels)
record['sign_positions'].add(sign_pos)
record['sign_positions'].add(tuple(sign['position']))
result = list(grouped.values())
result.sort(key=lambda chest: utils.phyp(center, chest['position']))
return result
def find_cache_chests(self, center, bot_name, distance=105):
"""Find bot/group-addressed general cache chests from signs."""
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)
grouped = {}
for sign in self.find_signs(center, distance):
text = ' '.join(line for line in sign['lines'] if line.strip())
tokens = re.findall(r'[a-z0-9_]+', text.casefold())
if (len(tokens) < 2 or tokens[0] not in addresses or
'cache' not in tokens[1:]):
continue
for chest in self._chests_associated_with_sign(sign):
positions = self._double_chest_positions(chest)
record = grouped.setdefault(positions, {
'position': tuple(chest),
'positions': positions,
'labels': set(),
'sign_positions': set(),
})
record['labels'].add('cache')
record['sign_positions'].add(tuple(sign['position']))
result = list(grouped.values())
result.sort(key=lambda chest: utils.phyp(center, chest['position']))
+67 -1
View File
@@ -1,7 +1,7 @@
import unittest
from munch import Munch
from mosfet.info import items
from mosfet.info import blocks, items
from mosfet.world import World
@@ -60,6 +60,72 @@ class StorageLabelTests(unittest.TestCase):
self.assertIn(items.WHEAT_SEEDS_ID, chests[0]['item_ids'])
self.assertEqual(chests[0]['labels'], {'Seeds'})
def test_general_cache_sign_matches_bot_group_and_prefers_side_chest(self):
sign_pos = (0, 64, 0)
side_chest = (1, 64, 0)
chest_below = (0, 63, 0)
sign_state = blocks.MCD_BLOCKS['oak_wall_sign']['minStateId']
chest_state = next(
state for state in blocks.CHEST_IDS
if blocks.PROPS[state].get('type') == 'single')
blocks_by_pos = {
sign_pos: sign_state,
side_chest: chest_state,
chest_below: chest_state,
}
chunks = Munch(
block_entities={sign_pos: {
'type': 7,
'data': {'front_text': {'messages': [
'mosfet cache', '', '', '',
]}},
}},
index={},
get_block_at=lambda *pos: blocks_by_pos.get(tuple(pos)),
)
world = World(Munch(chunks=chunks))
group_caches = world.find_cache_chests(sign_pos, 'mosfet2', 10)
self.assertEqual(len(group_caches), 1)
self.assertEqual(group_caches[0]['position'], side_chest)
self.assertEqual(group_caches[0]['positions'], (side_chest,))
self.assertEqual(world.find_cache_chests(
sign_pos, 'mosfet4', 10), [])
def test_side_chest_takes_priority_over_chest_below_sign(self):
sign_pos = (0, 64, 0)
side_chest = (1, 64, 0)
chest_below = (0, 63, 0)
sign_state = blocks.MCD_BLOCKS['oak_wall_sign']['minStateId']
chest_state = next(
state for state in blocks.CHEST_IDS
if blocks.PROPS[state].get('type') == 'single')
blocks_by_pos = {
sign_pos: sign_state,
side_chest: chest_state,
chest_below: chest_state,
}
chunks = Munch(
block_entities={sign_pos: {
'type': 7,
'data': {'front_text': {'messages': [
'Saplings', '', '', '',
]}},
}},
index={},
get_block_at=lambda *pos: blocks_by_pos.get(tuple(pos)),
)
chests = World(Munch(chunks=chunks)).find_labeled_chests(
sign_pos, 10)
self.assertEqual(len(chests), 1)
self.assertEqual(chests[0]['position'], side_chest)
self.assertEqual(chests[0]['positions'], (side_chest,))
self.assertNotIn(chest_below, chests[0]['positions'])
self.assertEqual(chests[0]['item_ids'], items.SAPLING_IDS)
if __name__ == '__main__':
unittest.main()
+29
View File
@@ -65,6 +65,35 @@ class ThrowSignTests(unittest.TestCase):
bot1 = world.find_throw_signs((0, 64, 0), 'mosfet1', 10)
self.assertEqual([sign['position'] for sign in bot1], [group_sign])
def test_throw_accepts_unqualified_items_and_species_log_labels(self):
single_item_sign = (0, 64, 0)
oak_family_sign = (4, 64, 0)
chunks = FakeChunks(
block_entities={
single_item_sign: {'data': {'front_text': {'messages': [
'mosfet1 throw oak_log', '', '', '',
]}}},
oak_family_sign: {'data': {'front_text': {'messages': [
'mosfet1 throw Oak Logs', '', '', '',
]}}},
},
states={
single_item_sign: wall_sign_state('north'),
oak_family_sign: wall_sign_state('north'),
})
world = World(Munch(chunks=chunks))
directives = world.find_throw_signs((0, 64, 0), 'mosfet1', 10)
exact = next(sign for sign in directives
if sign['position'] == single_item_sign)
family = next(sign for sign in directives
if sign['position'] == oak_family_sign)
self.assertEqual(exact['item_ids'], {items.get_id('oak_log')})
self.assertEqual(family['item_ids'], items.get_set({
'oak_log', 'stripped_oak_log', 'oak_wood', 'stripped_oak_wood',
}))
def test_back_text_uses_back_face_normal(self):
position = (0, 64, 0)
world = World(Munch(chunks=FakeChunks(