diff --git a/mosfet/bot.py b/mosfet/bot.py index 306a280..671f266 100644 --- a/mosfet/bot.py +++ b/mosfet/bot.py @@ -248,6 +248,10 @@ def tick(global_state): block_above = g.chunks.get_block_at(floor(p.x), ceil(p.y+1), floor(p.z)) in_void = p.y < 0 in_air = block_below in blocks.NON_SOLID_IDS or in_void + support_below = g.chunks.get_block_at( + floor(p.x), floor(p.y - 0.2), floor(p.z)) + g.on_ground = (support_below is not None and + support_below not in blocks.NON_SOLID_IDS and not in_void) in_water = block_below in blocks.WATER_IDS g.crawling = block_above not in blocks.NON_SOLID_IDS @@ -289,7 +293,7 @@ def tick(global_state): ) packet = PlayerPositionRotation( x=p.x, y=p.y, z=p.z, pitch=g.pitch, yaw=g.yaw, - on_ground=(not in_air)) + on_ground=g.on_ground) # Keep the client-tick boundary after its movement packet on the wire. g.connection.write_packet(packet, force=True) g.connection.write_packet(ClientTickEnd(), force=True) diff --git a/mosfet/game.py b/mosfet/game.py index 0d894c8..19b9b1f 100644 --- a/mosfet/game.py +++ b/mosfet/game.py @@ -681,8 +681,8 @@ class LegacyGame: # Active game facade. The constructor registers no legacy packet listeners; # migrated actions use the 26.3 packet classes imported above. class Game(LegacyGame): - ARM_SWING_INTERVAL = 0.1 - BREAK_FINISH_GRACE = 0.2 + ARM_SWING_INTERVAL = 0.35 + PENDING_GROUND_TIMEOUT = 1.0 DOOR_AUTO_OPEN_GRACE = 0.25 DOOR_TURN_DURATION = 0.3 @@ -691,6 +691,7 @@ class Game(LegacyGame): self.sequence = 0 self.break_deadline = None self.breaking_state = None + self.break_pending_since = None self.next_swing_at = 0.0 self.door_navigation = None self.g.yaw_target_override = None @@ -1012,43 +1013,68 @@ class Game(LegacyGame): block_id = self.g.chunks.get_block_at(*location) if block_id is None or block_id == blocks.AIR: return False + if self.g.get('breaking'): + return tuple(self.g.breaking) == location + if not self.g.get('on_ground', True): + now = time.monotonic() + self.g.breaking = location + self.breaking_state = block_id + self.break_pending_since = now + self.break_deadline = None + return True + return self._start_block_break(location, block_id) + def _start_block_break(self, location, block_id): holding = self.g.get('holding', 0) held_slot = (45 if self.g.get('holding_hand', 0) == 1 else 36 + int(self.g.get('holding_slot', 0) or 0)) held_stack = self.g.get('inv', {}).get(held_slot) - enchantments = (getattr(held_stack, 'components', {}) or {}).get( + enchantments = dict((getattr(held_stack, 'components', {}) or {}).get( + 'enchantments', {}) or {}) + helmet = self.g.get('inv', {}).get(5) + helmet_enchantments = (getattr(helmet, 'components', {}) or {}).get( 'enchantments', {}) + if isinstance(helmet_enchantments, dict): + enchantments.update(helmet_enchantments) + in_water = False - on_ground = True + on_ground = self.g.get('on_ground', True) position = self.g.get('pos') chunks = self.g.get('chunks') if position is not None and chunks is not None: x, y, z = (floor(position.x), floor(position.y), floor(position.z)) - support = chunks.get_block_at(x, floor(position.y - 0.2), z) - if support is not None: - on_ground = support not in blocks.NON_SOLID_IDS - feet = chunks.get_block_at(x, y, z) eyes = chunks.get_block_at(x, floor(position.y + 1.62), z) - in_water = feet in blocks.WATER_IDS or eyes in blocks.WATER_IDS + # Mineflayer applies the water penalty only when the eyes are + # submerged, and aqua affinity on the helmet cancels that penalty. + in_water = eyes in blocks.WATER_IDS + if 'on_ground' not in self.g: + support = chunks.get_block_at( + x, floor(position.y - 0.2), z) + if support is not None: + on_ground = support not in blocks.NON_SOLID_IDS + game_mode = self.g.get('game_mode') duration = utils.break_time( block_id, holding, in_water=in_water, on_ground=on_ground, - enchantments=enchantments, effects=self.g.get('effects', {})) + enchantments=enchantments, effects=self.g.get('effects', {}), + creative=(game_mode == 1 or game_mode == 'creative')) if not isfinite(duration): + self.g.breaking = None + self.breaking_state = None + self.break_pending_since = None return False + sequence = self._next_sequence() packet = PlayerActionPacket( action=0, location=location, face=1, - sequence=self._next_sequence()) + sequence=sequence) self._send_action(packet) self.g.breaking = location self.breaking_state = block_id now = time.monotonic() - # A server tick and packet delay can otherwise make the client finish - # just before the server has accumulated the full mining progress. - self.break_deadline = now + duration + self.BREAK_FINISH_GRACE + self.break_pending_since = None + self.break_deadline = now + duration self.animate() self.next_swing_at = now + self.ARM_SWING_INTERVAL return True @@ -1251,39 +1277,59 @@ class Game(LegacyGame): self._tick_dump() if self.g.get('draining'): self._tick_drain() - if not self.g.get('breaking') or self.break_deadline is None: + if not self.g.get('breaking'): return now = time.monotonic() - if now < self.break_deadline: - if now >= self.next_swing_at: - self.animate() - self.next_swing_at = now + self.ARM_SWING_INTERVAL - return - packet = PlayerActionPacket( - action=3, location=self.g.breaking, face=1, - sequence=self._next_sequence()) - self._send_action(packet) location = self.g.breaking - if self.g.chunks.get_block_at(*location) == self.breaking_state: - # Predict the normal client-side block removal. The server's later - # block update is authoritative and will correct the cache if the - # action was denied or the block changed differently. + current_block = self.g.chunks.get_block_at(*location) + if current_block != self.breaking_state: + self.g.breaking = None + self.break_deadline = None + self.breaking_state = None + self.break_pending_since = None + self.next_swing_at = 0.0 + return + if self.break_deadline is None: + pending_since = getattr(self, 'break_pending_since', None) + if pending_since is None: + pending_since = now + self.break_pending_since = now + if (not self.g.get('on_ground', True) and + now - pending_since < self.PENDING_GROUND_TIMEOUT): + return + self._start_block_break(location, current_block) + return + if now >= self.break_deadline: + sequence = self._next_sequence() + packet = PlayerActionPacket( + action=3, location=location, face=1, + sequence=sequence) + self._send_action(packet) + # Match Mineflayer's local prediction. The server's block update + # remains authoritative and will restore the cache if rejected. self.g.chunks.set_block_at(*location, blocks.AIR) - self.g.breaking = None - self.break_deadline = None - self.breaking_state = None - self.next_swing_at = 0.0 + self.g.breaking = None + self.break_deadline = None + self.breaking_state = None + self.break_pending_since = None + self.next_swing_at = 0.0 + return + if now >= self.next_swing_at: + self.animate() + self.next_swing_at = now + self.ARM_SWING_INTERVAL def cancel_break(self): if not self.g.get('breaking'): return - packet = PlayerActionPacket( - action=2, location=self.g.breaking, face=1, - sequence=self._next_sequence()) - self._send_action(packet) + if self.break_deadline is not None: + packet = PlayerActionPacket( + action=2, location=self.g.breaking, face=1, + sequence=self._next_sequence()) + self._send_action(packet) self.g.breaking = None self.break_deadline = None self.breaking_state = None + self.break_pending_since = None self.next_swing_at = 0.0 def select_item(self, item_ids, force=False): diff --git a/mosfet/utils.py b/mosfet/utils.py index ede549a..c574e03 100644 --- a/mosfet/utils.py +++ b/mosfet/utils.py @@ -121,48 +121,97 @@ def diffrange(n): sign = 1 if n >= 0 else -1 return range(0, n+sign, sign) +def _enchantment_level(enchantments, *names): + if isinstance(enchantments, dict): + for name in names: + value = enchantments.get(name) + if value is None: + continue + if isinstance(value, dict): + value = value.get('level', value.get('lvl', 0)) + return int(value or 0) + else: + for enchantment in enchantments or (): + if not isinstance(enchantment, dict): + continue + name = enchantment.get('name') + if isinstance(name, dict): + name = name.get('id', name.get('name')) + if any(str(name).endswith(candidate) for candidate in names): + return int(enchantment.get( + 'level', enchantment.get('lvl', 0)) or 0) + return 0 + + def break_time(block_id, held_item=0, in_water=False, on_ground=True, - enchantments=None, effects=None): - """Return vanilla block-breaking duration rounded to whole game ticks.""" + enchantments=None, effects=None, creative=False): + """Return Mineflayer-style vanilla dig time in seconds.""" + if creative: + return 0.0 + held_item = str(held_item) block_data = blocks.get(block_id) hardness = block_data.get('hardness', 0) if hardness < 0: return float('inf') + if hardness == 0: + return 0.0 - can_harvest = ( - 'harvestTools' not in block_data or - held_item in block_data['harvestTools']) + harvest_tools = block_data.get('harvestTools') + can_harvest = (not harvest_tools or + held_item in harvest_tools) material = block_data.get('material', 'n/a') tool_multipliers = mcdata.mcd.materials.get(material, {}) - speed = tool_multipliers.get(held_item, 1.0) + speed = tool_multipliers.get(held_item, 1.0) or 1.0 - enchantments = enchantments or {} - if speed > 1: - efficiency = int(enchantments.get( - 'efficiency', enchantments.get('minecraft:efficiency', 0)) or 0) - if efficiency > 0: - speed += efficiency * efficiency + 1 + efficiency = _enchantment_level( + enchantments, 'efficiency', 'minecraft:efficiency') + if efficiency > 0 and speed > 1.0: + speed += efficiency * efficiency + 1 effects = effects or {} - haste = int(effects.get('haste', effects.get('minecraft:haste', 0)) or 0) - if haste >= 0 and ('haste' in effects or 'minecraft:haste' in effects): - speed *= 1 + 0.2 * (haste + 1) - fatigue = int(effects.get( - 'mining_fatigue', effects.get('minecraft:mining_fatigue', -1))) - if fatigue >= 0: - speed *= (0.3, 0.09, 0.0027, 0.00081, 0.000243)[min(fatigue, 4)] - duration = hardness * (1.5 if can_harvest else 5.0) / speed - if in_water: - duration *= 5.0 + def effect_level(*names): + for name in names: + value = effects.get(name) + if value is None: + continue + if isinstance(value, dict): + amplifier = value.get('amplifier') + if amplifier is not None: + return int(amplifier) + 1 + return int(value.get('level', 0) or 0) + # Runtime effect dictionaries use zero-based amplifiers. + return int(value) + 1 + return 0 + + haste = max(effect_level('haste', 'minecraft:haste'), + effect_level('conduit_power', 'minecraft:conduit_power')) + if haste > 0: + speed *= 1 + 0.2 * haste + + fatigue = effect_level( + 'mining_fatigue', 'minecraft:mining_fatigue') + if fatigue > 0: + speed *= (0.3, 0.09, 0.0027, 0.00081, 0.000243)[ + min(fatigue, 4) - 1] + + if speed <= 0: + return float('inf') + + aqua_affinity = _enchantment_level( + enchantments, 'aqua_affinity', 'minecraft:aqua_affinity') + if in_water and aqua_affinity == 0: + speed /= 5.0 if not on_ground: - duration *= 5.0 + speed /= 5.0 - # Vanilla advances breaking progress in 1/20-second ticks; clients cannot - # finish between ticks. Round up, while avoiding floating-point over-round. - ticks = max(1, ceil(duration / TICK - 1e-9)) - return ticks * TICK + delta = speed / hardness / (30.0 if can_harvest else 100.0) + if delta <= 0: + return float('inf') + if delta >= 1.0: + return 0.0 + return ceil(1.0 / delta) * TICK def search_2d(distance=0): def get_neighbors(x,y,z): diff --git a/tests/test_break_animation.py b/tests/test_break_animation.py index af3af6b..57ade2a 100644 --- a/tests/test_break_animation.py +++ b/tests/test_break_animation.py @@ -1,11 +1,12 @@ import io import time import unittest +from unittest.mock import patch from munch import Munch from minecraft.networking.modern import ( ClientTickEnd, EntityAnimationPacket, EntitySwingAnimationPacket, - PunchPacket, + PlayerActionPacket, PunchPacket, ) from mosfet.game import Game @@ -22,7 +23,18 @@ class BlockBreakAnimationTests(unittest.TestCase): def make_game(self): connection = RecordingConnection() game = object.__new__(Game) - game.g = Munch(connection=connection, inv={}, inventory_state_ids={}) + class FakeChunks: + block = 10 + + def get_block_at(self, *_position): + return self.block + + def set_block_at(self, *_position): + self.block = 0 + + game.g = Munch( + connection=connection, inv={}, inventory_state_ids={}, + chunks=FakeChunks()) game.sequence = 0 game.break_deadline = None game.breaking_state = None @@ -54,24 +66,33 @@ class BlockBreakAnimationTests(unittest.TestCase): [PunchPacket, ClientTickEnd]) self.assertTrue(all(force for _, force in connection.packets)) - def test_breaking_sends_initial_and_periodic_punches(self): + def test_breaking_sends_finish_and_predicts_block_air(self): game, connection = self.make_game() + game._advance_world_time = lambda: None + game._tick_single_drop = lambda: None game.g.breaking = (1, 2, 3) - game.break_deadline = time.monotonic() + 5 + game.break_deadline = 101.0 game.breaking_state = 10 game.next_swing_at = 0 - game.tick() - self.assertEqual(sum(isinstance(packet, PunchPacket) - for packet, _ in connection.packets), 1) - sent = len(connection.packets) - game.tick() - self.assertEqual(len(connection.packets), sent) + with patch('mosfet.game.time.monotonic', return_value=100.0): + game.tick() + self.assertEqual(sum(isinstance(packet, PunchPacket) + for packet, _ in connection.packets), 1) + sent = len(connection.packets) + game.tick() + self.assertEqual(len(connection.packets), sent) - game.next_swing_at = 0 - game.tick() - self.assertEqual(sum(isinstance(packet, PunchPacket) - for packet, _ in connection.packets), 2) + game.break_deadline = 99.0 + with patch('mosfet.game.time.monotonic', return_value=100.0): + game.tick() + actions = [packet.action for packet, _ in connection.packets + if isinstance(packet, PlayerActionPacket)] + self.assertEqual(actions, [3]) + self.assertIsNone(game.g.breaking) + sent = len(connection.packets) + game.tick() + self.assertEqual(len(connection.packets), sent) if __name__ == '__main__': diff --git a/tests/test_break_time.py b/tests/test_break_time.py index c6eb0e0..55b1f53 100644 --- a/tests/test_break_time.py +++ b/tests/test_break_time.py @@ -2,10 +2,12 @@ import math import unittest from unittest.mock import patch from munch import Munch +from minecraft.networking.modern import PlayerActionPacket from mosfet import utils from mosfet.game import Game from mosfet.info import blocks, items +from mosfet.vector import Point3D class BlockBreakTimingTests(unittest.TestCase): @@ -21,6 +23,17 @@ class BlockBreakTimingTests(unittest.TestCase): self.assertAlmostEqual( utils.break_time(oak_leaves, oak_log, on_ground=False), 1.5) + def test_dig_time_uses_eye_submersion_and_aqua_affinity(self): + sand = blocks.MCD_BLOCKS['sand']['minStateId'] + wooden_shovel = items.get_id('wooden_shovel') + + self.assertEqual(utils.break_time(sand, wooden_shovel), 0.4) + self.assertAlmostEqual( + utils.break_time(sand, wooden_shovel, in_water=True), 1.9) + self.assertEqual(utils.break_time( + sand, wooden_shovel, in_water=True, + enchantments={'minecraft:aqua_affinity': 1}), 0.4) + def test_efficiency_haste_and_fatigue_affect_break_ticks(self): oak_leaves = blocks.MCD_BLOCKS['oak_leaves']['minStateId'] wooden_hoe = items.get_id('wooden_hoe') @@ -36,7 +49,7 @@ class BlockBreakTimingTests(unittest.TestCase): bedrock = blocks.MCD_BLOCKS['bedrock']['minStateId'] self.assertTrue(math.isinf(utils.break_time(bedrock))) - def test_game_sends_finish_after_calculated_tick_duration(self): + def test_dig_request_waits_until_grounded_before_starting(self): class RecordingConnection: def __init__(self): self.packets = [] @@ -45,9 +58,62 @@ class BlockBreakTimingTests(unittest.TestCase): self.packets.append(packet) class FakeChunks: - @staticmethod - def get_block_at(*_position): - return blocks.MCD_BLOCKS['oak_leaves']['minStateId'] + state = blocks.MCD_BLOCKS['sand']['minStateId'] + + def get_block_at(self, *_position): + return self.state + + def set_block_at(self, *_position): + self.state = blocks.AIR + + connection = RecordingConnection() + game = object.__new__(Game) + game.g = Munch( + connection=connection, chunks=FakeChunks(), inv={}, + holding=items.get_id('wooden_shovel'), holding_hand=0, + holding_slot=0, pos=Point3D((0.0, 64.0, 0.0)), + on_ground=False, breaking=None, game_mode=0) + game.sequence = 0 + game.break_deadline = None + game.breaking_state = None + game.break_pending_since = None + game.next_swing_at = 0.0 + game._advance_world_time = lambda: None + game._tick_single_drop = lambda: None + + with patch('mosfet.game.time.monotonic', return_value=100.0): + self.assertTrue(game.break_block((0, 63, 0))) + self.assertEqual(connection.packets, []) + with patch('mosfet.game.time.monotonic', return_value=100.5): + game.tick() + self.assertEqual(connection.packets, []) + + game.g.on_ground = True + with patch('mosfet.game.time.monotonic', return_value=100.6): + game.tick() + + self.assertEqual(sum(isinstance(packet, PlayerActionPacket) + for packet in connection.packets), 1) + self.assertEqual(connection.packets[0].action, 0) + self.assertAlmostEqual(game.break_deadline, 101.0) + + def test_game_finishes_at_dig_time_and_predicts_block_air(self): + class RecordingConnection: + def __init__(self): + self.packets = [] + + def write_packet(self, packet, force=False): + self.packets.append(packet) + + class FakeChunks: + def __init__(self): + self.block = blocks.MCD_BLOCKS['oak_leaves']['minStateId'] + + def get_block_at(self, *_position): + return self.block + + def set_block_at(self, *_position): + self.block = blocks.AIR connection = RecordingConnection() game = object.__new__(Game) @@ -62,9 +128,19 @@ class BlockBreakTimingTests(unittest.TestCase): with patch('mosfet.game.time.monotonic', return_value=100.0): self.assertTrue(game.break_block((0, 64, 0))) - self.assertAlmostEqual( - game.break_deadline, - 100.3 + game.BREAK_FINISH_GRACE) + self.assertAlmostEqual(game.break_deadline, 100.3) + + game._advance_world_time = lambda: None + game._tick_single_drop = lambda: None + with patch('mosfet.game.time.monotonic', + return_value=game.break_deadline): + game.tick() + + actions = [packet.action for packet in connection.packets + if isinstance(packet, PlayerActionPacket)] + self.assertEqual(actions, [0, 3]) + self.assertIsNone(game.g.breaking) + self.assertEqual(game.g.chunks.block, blocks.AIR) if __name__ == '__main__':