Skip to main content

ghast_client/
hands.rs

1//! The mouse buttons in the world: digging, placing, using items and hitting or using
2//! entities, as vanilla's key handling does it (`MinecraftClient.tick`: `doAttack`, `doUse`,
3//! `handleBlockBreaking`; `ClientPlayerInteractionManager`: `attackBlock`,
4//! `updateBlockBreakingProgress`, `cancelBlockBreaking`, `interactBlock`, `interactItem`,
5//! `attackEntity`, `stopUsingItem`). The 1.8.9 rules were checked against recorded lab packet
6//! traces; the modern dig timing and the 26.x packets against the oracle and vanilla captures.
7//!
8//! The hands run once per tick after the behaviour and before the movement step (vanilla's
9//! key processing comes after the tick-start event and before the player's update), so their
10//! packets precede this tick's movement packet and the server judges them with the previous
11//! tick's pose.
12//!
13//! One state machine serves every version; the version's capability row picks the rules.
14//! 1.8: the swing comes before the dig or attack, the right button uses the held stack only.
15//! 1.9+ (1.12.2, 1.16.5, 26.x): the dig or attack comes before the swing, the attack strength
16//! (cooldown) is tracked, the right button tries the main hand and then the off hand, and item
17//! uses count their ticks and are released like vanilla's. Version-specific facts (block
18//! hardness, tool groups, selection boxes, the held stack, destroy-progress formulas) come
19//! from the [`BlockQuery`] answers and [`HeldItem`].
20//!
21//! **Entities are seen only with entity tracking**
22//! ([`Interests::ENTITIES`](crate::Interests::ENTITIES) or
23//! [`Interests::ENTITY_TRACKING`](crate::Interests::ENTITY_TRACKING)). Without it the crosshair is a block pick: a player or mob between the eyes and the
24//! block neither stops the dig nor can be attacked or used, and nothing pushes the player.
25
26use ghast_data::DigMaterial;
27use ghast_protocol::BlockPos;
28
29use crate::common::{DigStatus, Face, Outbound, Vec3};
30
31/// Survival block reach (`ClientPlayerInteractionManager.getReachDistance`).
32pub const REACH: f64 = 4.5;
33
34/// What the hands need to know about one block state.
35#[derive(Debug, Clone, Copy, PartialEq)]
36#[non_exhaustive]
37pub struct BlockQuery {
38    /// The block is air (`Material.AIR`).
39    pub air: bool,
40    /// The block is water (eyes in it slow digging).
41    pub water: bool,
42    /// Version block id (1.8 `id`, 1.16 registry id).
43    pub block: u16,
44    /// Hardness; negative = unbreakable.
45    pub hardness: f32,
46    /// Tool group for the speed multiplier.
47    pub dig_material: Option<DigMaterial>,
48    /// Item ids that harvest the block (empty = any).
49    pub harvest_tools: &'static [u16],
50    /// Selection (ray) box relative to the block, `None` when rays pass through.
51    pub selection: Option<[f64; 6]>,
52    /// Stairs (1.8): vanilla's eight-pass half-cube ray test; the passes' block-local boxes
53    /// (`None` = skipped pass). When set, `selection` is ignored for rays.
54    pub stairs: Option<[Option<[f64; 6]>; 8]>,
55    /// Right-clicking the block activates it (containers, doors, levers, …).
56    pub activates: bool,
57    /// The version's oracle-verified destroy progress (`ghast_data::<version>::dig`); `None`
58    /// uses the generic formula over `hardness` / `dig_material` / `harvest_tools`.
59    pub(crate) exact: Option<ExactDig>,
60}
61
62/// Which jar-derived destroy-progress function digs the block.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub(crate) enum ExactDig {
65    /// `ghast_data::v1_8::dig` (block id in [`BlockQuery::block`]).
66    #[cfg(feature = "v1_8")]
67    V1_8,
68    /// `ghast_data::v1_12::dig`.
69    #[cfg(feature = "v1_12_2")]
70    V1_12,
71    /// `ghast_data::v1_16_5::dig`.
72    #[cfg(feature = "v1_16_5")]
73    V1_16_5,
74    /// `ghast_data::v26_1::dig` with the player's mining attributes.
75    #[cfg(feature = "v26_1")]
76    V26_1(ModernDig),
77    /// `ghast_data::v26_2::dig` with the player's mining attributes.
78    #[cfg(feature = "v26_2")]
79    V26_2(ModernDig),
80    /// `ghast_data::v26_3::dig` with the player's mining attributes.
81    #[cfg(feature = "v26_3")]
82    V26_3(ModernDig),
83}
84
85/// The facts of the modern destroy-progress formula (attributes replace enchantment levels).
86#[cfg(ghast_modern)]
87#[derive(Debug, Clone, Copy, PartialEq)]
88pub(crate) struct ModernDig {
89    /// Block state id.
90    pub(crate) state: u16,
91    /// `minecraft:mining_efficiency`.
92    pub(crate) mining_efficiency: f64,
93    /// `minecraft:block_break_speed`.
94    pub(crate) block_break_speed: f64,
95    /// `minecraft:submerged_mining_speed`.
96    pub(crate) submerged_mining_speed: f64,
97    /// Conduit power amplifier.
98    pub(crate) conduit_power: Option<i32>,
99}
100
101/// 1.9+ `getAttackCooldownProgress(0.5F)` after `ticks` ticks since the last swing:
102/// `clamp((ticks + 0.5) / (float)(1 / attack_speed * 20), 0, 1)`.
103pub(crate) fn attack_strength_at(ticks: u32, attack_speed: f64) -> f32 {
104    let period = (1.0 / attack_speed * 20.0) as f32;
105    ((ticks as f32 + 0.5) / period).clamp(0.0, 1.0)
106}
107
108/// The held stack as far as digging and using need it.
109#[derive(Debug, Clone, Copy, Default)]
110#[non_exhaustive]
111pub struct HeldItem {
112    /// Item id.
113    pub id: u16,
114    /// Stack size.
115    pub count: u8,
116    /// Efficiency enchantment level.
117    pub efficiency: u8,
118    /// The item places a block (`BlockItem`).
119    pub places_block: bool,
120    /// The item is used by holding right click (food, potion, bow, sword, milk).
121    pub usable: bool,
122    /// The item is food (eaten only below a full food bar).
123    pub food: bool,
124    /// Food that can be eaten at any food level (golden apple).
125    pub always_edible: bool,
126    /// Tool speed multiplier per dig group, filled by the version (`tool_multiplier`).
127    pub tool_speed: Option<fn(DigMaterial, u16) -> f32>,
128    /// 1.20.5+: the item id for the exact destroy progress (`ghast_data::v26_1`).
129    #[cfg_attr(not(ghast_modern), allow(dead_code))]
130    pub(crate) modern_item: Option<u16>,
131    /// Using the item succeeds on the client and swings the arm (26.1: a firework rocket while
132    /// gliding, `FireworkRocketItem.use`).
133    pub(crate) swing_on_use: bool,
134    /// Using the item puts it on (`ArmorItem.use` and the like: the inventory's
135    /// `use_equips`); filled by the engine only for its key handling.
136    pub(crate) equips: bool,
137    /// That equip swings the arm (1.16.5 / 26.x SUCCESS; 1.8 / 1.12.2 do not).
138    pub(crate) equip_swings: bool,
139    /// The item breaks no block in creative (1.8 / 1.12 `breakBlock`, 1.16.5 `canMine`:
140    /// swords, the trident); the dig packets still go out.
141    pub(crate) creative_keeps_blocks: bool,
142    /// 1.12: the item's use answers SUCCESS without holding (thrown items, the fishing rod):
143    /// the click ends with it (no off hand), without a swing.
144    pub(crate) use_succeeds: bool,
145}
146
147impl BlockQuery {
148    /// A solid, instantly breakable block with no tool group, no ray box and no activation;
149    /// set the rest with the `with_*` methods.
150    #[must_use]
151    pub const fn new(block: u16) -> Self {
152        BlockQuery {
153            exact: None,
154            air: false,
155            water: false,
156            block,
157            hardness: 0.0,
158            dig_material: None,
159            harvest_tools: &[],
160            selection: None,
161            stairs: None,
162            activates: false,
163        }
164    }
165
166    /// Air (id 0, no ray box).
167    pub const AIR: BlockQuery = BlockQuery::new(0).with_air(true);
168
169    /// The block is air.
170    #[must_use]
171    pub const fn with_air(mut self, on: bool) -> Self {
172        self.air = on;
173        self
174    }
175
176    /// The block is water.
177    #[must_use]
178    pub const fn with_water(mut self, on: bool) -> Self {
179        self.water = on;
180        self
181    }
182
183    /// Hardness (negative: unbreakable).
184    #[must_use]
185    pub const fn with_hardness(mut self, hardness: f32) -> Self {
186        self.hardness = hardness;
187        self
188    }
189
190    /// Tool group.
191    #[must_use]
192    pub const fn with_dig_material(mut self, m: Option<DigMaterial>) -> Self {
193        self.dig_material = m;
194        self
195    }
196
197    /// Item ids that harvest the block (empty: any).
198    #[must_use]
199    pub const fn with_harvest_tools(mut self, tools: &'static [u16]) -> Self {
200        self.harvest_tools = tools;
201        self
202    }
203
204    /// Selection (ray) box relative to the block.
205    #[must_use]
206    pub const fn with_selection(mut self, b: Option<[f64; 6]>) -> Self {
207        self.selection = b;
208        self
209    }
210
211    /// 1.8 stairs ray passes.
212    #[must_use]
213    pub const fn with_stairs(mut self, passes: Option<[Option<[f64; 6]>; 8]>) -> Self {
214        self.stairs = passes;
215        self
216    }
217
218    /// Right-clicking activates it.
219    #[must_use]
220    pub const fn with_activates(mut self, on: bool) -> Self {
221        self.activates = on;
222        self
223    }
224}
225
226impl HeldItem {
227    /// One item of `id` with nothing else known; set the rest with the `with_*` methods.
228    #[must_use]
229    pub const fn new(id: u16) -> Self {
230        HeldItem {
231            modern_item: None,
232            swing_on_use: false,
233            equips: false,
234            equip_swings: false,
235            creative_keeps_blocks: false,
236            use_succeeds: false,
237            id,
238            count: 1,
239            efficiency: 0,
240            places_block: false,
241            usable: false,
242            food: false,
243            always_edible: false,
244            tool_speed: None,
245        }
246    }
247
248    /// Stack size.
249    #[must_use]
250    pub const fn with_count(mut self, count: u8) -> Self {
251        self.count = count;
252        self
253    }
254
255    /// Efficiency level.
256    #[must_use]
257    pub const fn with_efficiency(mut self, level: u8) -> Self {
258        self.efficiency = level;
259        self
260    }
261
262    /// The item places a block.
263    #[must_use]
264    pub const fn with_places_block(mut self, on: bool) -> Self {
265        self.places_block = on;
266        self
267    }
268
269    /// The item is used by holding right click.
270    #[must_use]
271    pub const fn with_usable(mut self, on: bool) -> Self {
272        self.usable = on;
273        self
274    }
275
276    /// Food (and whether it can be eaten at a full food bar).
277    #[must_use]
278    pub const fn with_food(mut self, food: bool, always_edible: bool) -> Self {
279        self.food = food;
280        self.always_edible = always_edible;
281        self
282    }
283
284    /// Tool speed per dig group.
285    #[must_use]
286    pub const fn with_tool_speed(mut self, f: Option<fn(DigMaterial, u16) -> f32>) -> Self {
287        self.tool_speed = f;
288        self
289    }
290}
291
292impl DigFactors {
293    /// On ground.
294    #[must_use]
295    pub const fn with_on_ground(mut self, on: bool) -> Self {
296        self.on_ground = on;
297        self
298    }
299
300    /// Eyes in water.
301    #[must_use]
302    pub const fn with_in_water(mut self, on: bool) -> Self {
303        self.in_water = on;
304        self
305    }
306
307    /// Aqua affinity on the helmet.
308    #[must_use]
309    pub const fn with_aqua_affinity(mut self, on: bool) -> Self {
310        self.aqua_affinity = on;
311        self
312    }
313
314    /// Haste level (amplifier + 1), 0 = none.
315    #[must_use]
316    pub const fn with_haste(mut self, level: u8) -> Self {
317        self.haste = level;
318        self
319    }
320
321    /// Mining fatigue level (amplifier + 1), 0 = none.
322    #[must_use]
323    pub const fn with_fatigue(mut self, level: u8) -> Self {
324        self.fatigue = level;
325        self
326    }
327}
328
329/// Mining speed modifiers of the player.
330#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
331#[non_exhaustive]
332pub struct DigFactors {
333    /// On ground.
334    pub on_ground: bool,
335    /// Eyes in water.
336    pub in_water: bool,
337    /// Aqua affinity on the helmet.
338    pub aqua_affinity: bool,
339    /// Haste level (amplifier + 1), 0 = none.
340    pub haste: u8,
341    /// Mining fatigue level (amplifier + 1), 0 = none.
342    pub fatigue: u8,
343}
344
345/// The version's destroy progress per tick (oracle-verified functions of `ghast-data`).
346fn exact_progress(b: &BlockQuery, e: ExactDig, held: Option<&HeldItem>, f: DigFactors) -> f32 {
347    let item = held.map(|h| h.id);
348    let efficiency = held.map_or(0, |h| h.efficiency);
349    let amp = |level: u8| (level > 0).then(|| i32::from(level) - 1);
350    let _ = (item, efficiency, &amp, b);
351    match e {
352        #[cfg(feature = "v1_8")]
353        ExactDig::V1_8 => ghast_data::v1_8::dig::destroy_progress(
354            item,
355            b.block,
356            &ghast_data::v1_8::dig::DigConditions {
357                efficiency,
358                haste: amp(f.haste),
359                mining_fatigue: amp(f.fatigue),
360                eye_in_water: f.in_water,
361                aqua_affinity: f.aqua_affinity,
362                on_ground: f.on_ground,
363            },
364        ),
365        #[cfg(feature = "v1_12_2")]
366        ExactDig::V1_12 => ghast_data::v1_12::dig::destroy_progress(
367            item,
368            b.block,
369            &ghast_data::v1_12::dig::DigConditions {
370                efficiency,
371                haste: amp(f.haste),
372                mining_fatigue: amp(f.fatigue),
373                eye_in_water: f.in_water,
374                aqua_affinity: f.aqua_affinity,
375                on_ground: f.on_ground,
376            },
377        ),
378        #[cfg(feature = "v1_16_5")]
379        ExactDig::V1_16_5 => ghast_data::v1_16_5::dig::destroy_progress(
380            item,
381            b.block,
382            &ghast_data::v1_16_5::dig::DigConditions {
383                efficiency,
384                haste: amp(f.haste),
385                conduit_power: None,
386                mining_fatigue: amp(f.fatigue),
387                eye_in_water: f.in_water,
388                aqua_affinity: f.aqua_affinity,
389                on_ground: f.on_ground,
390            },
391        ),
392        #[cfg(feature = "v26_1")]
393        ExactDig::V26_1(m) => crate::sim::v26_1::dig_progress(&m, held, f),
394        #[cfg(feature = "v26_2")]
395        ExactDig::V26_2(m) => crate::sim::v26_2::dig_progress(&m, held, f),
396        #[cfg(feature = "v26_3")]
397        ExactDig::V26_3(m) => crate::sim::v26_3::dig_progress(&m, held, f),
398    }
399}
400
401/// `Block.calcBlockBreakingData` (float maths): break progress per tick.
402#[must_use]
403pub fn relative_hardness(b: &BlockQuery, held: Option<&HeldItem>, f: DigFactors) -> f32 {
404    if let Some(e) = b.exact {
405        return exact_progress(b, e, held, f);
406    }
407    let h = b.hardness;
408    if h < 0.0 {
409        return 0.0;
410    }
411    let can_harvest =
412        b.harvest_tools.is_empty() || held.is_some_and(|i| b.harvest_tools.contains(&i.id));
413    // PlayerEntity.getMiningSpeed
414    let mut speed = match (held, b.dig_material) {
415        (Some(i), Some(m)) => i.tool_speed.map_or(1.0, |t| t(m, i.id)),
416        _ => 1.0,
417    };
418    if speed > 1.0
419        && let Some(i) = held
420        && i.efficiency > 0
421    {
422        let e = f32::from(i.efficiency);
423        speed += e * e + 1.0;
424    }
425    if f.haste > 0 {
426        speed *= 1.0 + f32::from(f.haste) * 0.2;
427    }
428    if f.fatigue > 0 {
429        speed *= match f.fatigue {
430            1 => 0.3,
431            2 => 0.09,
432            3 => 0.0027,
433            _ => 8.1e-4,
434        };
435    }
436    if f.in_water && !f.aqua_affinity {
437        speed /= 5.0;
438    }
439    if !f.on_ground {
440        speed /= 5.0;
441    }
442    if can_harvest {
443        speed / h / 30.0
444    } else {
445        speed / h / 100.0
446    }
447}
448
449/// `Entity.getRotationVector(pitch, yaw)` with vanilla's float sine table.
450#[must_use]
451pub fn look_vector(yaw: f32, pitch: f32) -> Vec3 {
452    use ghast_physics::math::{cos, sin};
453    const RAD: f32 = 0.017_453_292;
454    let f = cos(-yaw * RAD - std::f32::consts::PI);
455    let f1 = sin(-yaw * RAD - std::f32::consts::PI);
456    let f2 = -cos(-pitch * RAD);
457    let f3 = sin(-pitch * RAD);
458    Vec3::new(f64::from(f1 * f2), f64::from(f3), f64::from(f * f2))
459}
460
461/// A block the crosshair is on.
462#[derive(Debug, Clone, Copy, PartialEq)]
463#[non_exhaustive]
464pub struct BlockHit {
465    /// The block.
466    pub pos: BlockPos,
467    /// The face hit.
468    pub face: Face,
469    /// The point hit (absolute).
470    pub hit: Vec3,
471    /// Distance from the eyes.
472    pub distance: f64,
473}
474
475/// The farthest a block hit lies from the eyes when the ray started inside the block's outline
476/// (1.14+ `insideBlock`): vanilla then hits at the ray's first test point, `0.001` of the reach
477/// ahead (4.5 or creative 5 blocks); any nearer face puts that point inside the block too.
478const INSIDE_HIT: f64 = 0.0051;
479
480/// Floor of a coordinate as vanilla's `MathHelper.floor`.
481fn floor(v: f64) -> i32 {
482    let i = v as i32;
483    if v < f64::from(i) { i - 1 } else { i }
484}
485
486/// `Vec3d.lerpForX` and friends: the point on the segment `a → b` whose `axis`
487/// coordinate is `v`, if it lies within the segment.
488fn intermediate(a: Vec3, b: Vec3, axis: usize, v: f64) -> Option<Vec3> {
489    let d = [b.x - a.x, b.y - a.y, b.z - a.z];
490    let o = [a.x, a.y, a.z];
491    if d[axis] * d[axis] < 1.0e-7 {
492        return None;
493    }
494    let t = (v - o[axis]) / d[axis];
495    (0.0..=1.0)
496        .contains(&t)
497        .then(|| Vec3::new(a.x + d[0] * t, a.y + d[1] * t, a.z + d[2] * t))
498}
499
500fn sq_dist(a: Vec3, b: Vec3) -> f64 {
501    let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
502    x * x + y * y + z * z
503}
504
505/// `Block.rayTrace`: the segment against the block's ray bounds, in
506/// block-local coordinates; the nearest of the six plane hits (ties go to the earlier plane:
507/// west, east, down, up, north, south).
508fn block_ray(pos: BlockPos, b: &[f64; 6], start: Vec3, end: Vec3) -> Option<(Vec3, Face)> {
509    let off = Vec3::new(f64::from(pos.x), f64::from(pos.y), f64::from(pos.z));
510    let s = Vec3::new(start.x - off.x, start.y - off.y, start.z - off.z);
511    let e = Vec3::new(end.x - off.x, end.y - off.y, end.z - off.z);
512    let in_yz = |v: &Vec3| v.y >= b[1] && v.y <= b[4] && v.z >= b[2] && v.z <= b[5];
513    let in_xz = |v: &Vec3| v.x >= b[0] && v.x <= b[3] && v.z >= b[2] && v.z <= b[5];
514    let in_xy = |v: &Vec3| v.x >= b[0] && v.x <= b[3] && v.y >= b[1] && v.y <= b[4];
515    let candidates = [
516        (intermediate(s, e, 0, b[0]).filter(in_yz), Face::West),
517        (intermediate(s, e, 0, b[3]).filter(in_yz), Face::East),
518        (intermediate(s, e, 1, b[1]).filter(in_xz), Face::Down),
519        (intermediate(s, e, 1, b[4]).filter(in_xz), Face::Up),
520        (intermediate(s, e, 2, b[2]).filter(in_xy), Face::North),
521        (intermediate(s, e, 2, b[5]).filter(in_xy), Face::South),
522    ];
523    let mut best: Option<(Vec3, Face)> = None;
524    for (v, face) in candidates {
525        if let Some(v) = v
526            && best.is_none_or(|(bv, _)| sq_dist(s, v) < sq_dist(s, bv))
527        {
528            best = Some((v, face));
529        }
530    }
531    best.map(|(v, f)| (Vec3::new(v.x + off.x, v.y + off.y, v.z + off.z), f))
532}
533
534/// What a ray found.
535#[derive(Debug, Clone, Copy, PartialEq)]
536#[non_exhaustive]
537pub enum RayResult {
538    /// A block's ray bounds.
539    Block(BlockHit),
540    /// Nothing; the last block the ray passed that rays go through (vanilla's "miss" result
541    /// of the crosshair pick).
542    Miss {
543        /// That block.
544        pos: BlockPos,
545        /// The face the ray entered it through.
546        face: Face,
547        /// The entry point.
548        hit: Vec3,
549    },
550    /// Nothing at all.
551    None,
552}
553
554/// 1.8 `World.rayTrace(start, end, false, false, return_last)`: walks the blocks from `start`
555/// to `end` exactly like vanilla (at most 200 steps; −1e−4 for a −0 plane fraction) and tests
556/// each block whose rays collide (`BlockQuery::selection`). Unloaded blocks read as air like
557/// the vanilla client's empty chunks.
558pub fn ray_trace(
559    blocks: &dyn Fn(i32, i32, i32) -> Option<BlockQuery>,
560    start: Vec3,
561    end: Vec3,
562    return_last: bool,
563) -> RayResult {
564    let nan = |v: Vec3| v.x.is_nan() || v.y.is_nan() || v.z.is_nan();
565    if nan(start) || nan(end) {
566        return RayResult::None;
567    }
568    let dist = |hit: Vec3, eyes: Vec3| sq_dist(eyes, hit).sqrt();
569    let eyes = start;
570    let (ex, ey, ez) = (floor(end.x), floor(end.y), floor(end.z));
571    let (mut x, mut y, mut z) = (floor(start.x), floor(start.y), floor(start.z));
572    let test = |p: BlockPos, s: Vec3| -> Option<BlockHit> {
573        let b = blocks(p.x, p.y, p.z)?;
574        let found = if let Some(passes) = &b.stairs {
575            // StairsBlock.rayTrace: the pass hit farthest from the ray's end wins (strictly;
576            // ties keep the earlier pass).
577            let mut best: Option<(Vec3, Face)> = None;
578            let mut best_d = 0.0;
579            for bounds in passes.iter().flatten() {
580                if let Some((hit, face)) = block_ray(p, bounds, s, end) {
581                    let d = sq_dist(hit, end);
582                    if d > best_d {
583                        best = Some((hit, face));
584                        best_d = d;
585                    }
586                }
587            }
588            best
589        } else {
590            block_ray(p, &b.selection?, s, end)
591        };
592        found.map(|(hit, face)| BlockHit {
593            pos: p,
594            face,
595            hit,
596            distance: dist(hit, eyes),
597        })
598    };
599    let first = BlockPos::new(x, y, z);
600    if let Some(h) = test(first, start) {
601        return RayResult::Block(h);
602    }
603    let mut last = RayResult::None;
604    let mut cur = start;
605    let mut steps = 200;
606    while steps >= 0 {
607        steps -= 1;
608        if nan(cur) {
609            return RayResult::None;
610        }
611        if x == ex && y == ey && z == ez {
612            break;
613        }
614        let plane = |e: i32, c: i32| {
615            if e > c {
616                Some(f64::from(c) + 1.0)
617            } else if e < c {
618                Some(f64::from(c))
619            } else {
620                None
621            }
622        };
623        let (px, py, pz) = (plane(ex, x), plane(ey, y), plane(ez, z));
624        let (dx, dy, dz) = (end.x - cur.x, end.y - cur.y, end.z - cur.z);
625        let frac = |p: Option<f64>, o: f64, d: f64| {
626            let t = p.map_or(999.0, |p| (p - o) / d);
627            // Vanilla's `t == -0.0` also matches +0.0: any zero fraction becomes -1e-4.
628            if t == 0.0 { -1.0e-4 } else { t }
629        };
630        let (tx, ty, tz) = (
631            frac(px, cur.x, dx),
632            frac(py, cur.y, dy),
633            frac(pz, cur.z, dz),
634        );
635        let face;
636        if tx < ty && tx < tz {
637            face = if ex > x { Face::West } else { Face::East };
638            cur = Vec3::new(px.unwrap_or(999.0), cur.y + dy * tx, cur.z + dz * tx);
639        } else if ty < tz {
640            face = if ey > y { Face::Down } else { Face::Up };
641            cur = Vec3::new(cur.x + dx * ty, py.unwrap_or(999.0), cur.z + dz * ty);
642        } else {
643            face = if ez > z { Face::North } else { Face::South };
644            cur = Vec3::new(cur.x + dx * tz, cur.y + dy * tz, pz.unwrap_or(999.0));
645        }
646        x = floor(cur.x) - i32::from(face == Face::East);
647        y = floor(cur.y) - i32::from(face == Face::Up);
648        z = floor(cur.z) - i32::from(face == Face::South);
649        let p = BlockPos::new(x, y, z);
650        match blocks(x, y, z).filter(|b| b.selection.is_some() || b.stairs.is_some()) {
651            Some(_) => {
652                if let Some(h) = test(p, cur) {
653                    return RayResult::Block(h);
654                }
655            }
656            None => {
657                last = RayResult::Miss {
658                    pos: p,
659                    face,
660                    hit: cur,
661                }
662            }
663        }
664    }
665    if return_last { last } else { RayResult::None }
666}
667
668/// The crosshair block: `Entity.rayTrace(reach)` from `eyes` along `look`.
669#[must_use]
670pub fn pick(
671    blocks: &dyn Fn(i32, i32, i32) -> Option<BlockQuery>,
672    eyes: Vec3,
673    look: Vec3,
674    reach: f64,
675) -> Option<BlockHit> {
676    let end = Vec3::new(
677        eyes.x + look.x * reach,
678        eyes.y + look.y * reach,
679        eyes.z + look.z * reach,
680    );
681    match ray_trace(blocks, eyes, end, true) {
682        RayResult::Block(h) => Some(h),
683        _ => None,
684    }
685}
686
687/// An entity the crosshair is on.
688#[derive(Debug, Clone, Copy, PartialEq)]
689#[non_exhaustive]
690pub struct EntityHit {
691    /// The entity id.
692    pub id: i32,
693    /// The point hit (absolute; the eyes when they are inside the box).
694    pub hit: Vec3,
695    /// The entity's position (for interact-at offsets).
696    pub entity_pos: Vec3,
697    /// Distance from the eyes.
698    pub distance: f64,
699    /// What the entity's client-side interact returns for the main and the off hand
700    /// (whether the item use follows) and what it does to that hand's stack.
701    pub(crate) interact: [(Interact, InteractEffect); 2],
702}
703
704/// What a handled (or fallen-through) entity click does to the hand's stack on the client.
705#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
706// Built by the 1.8 / 1.12 / 1.16.5 tables only (Damage by 1.8 / 1.12).
707#[cfg_attr(not(any(feature = "v1_8", feature = "v1_12_2")), allow(dead_code))]
708pub(crate) enum InteractEffect {
709    /// Nothing.
710    #[default]
711    None,
712    /// One item less (a lead, a saddle, a dye, a breeding food, a bone).
713    Take,
714    /// One point of damage (shears on a sheep).
715    Damage,
716    /// The last item becomes a milk bucket (a bucket on a cow); a stack of more loses one.
717    IntoMilk,
718    /// 26.x: the last item becomes this item (raw id: a filled bucket, a stew); a stack of more
719    /// loses one.
720    #[cfg_attr(
721        not(any(feature = "v26_1", feature = "v26_2", feature = "v26_3")),
722        allow(dead_code)
723    )]
724    Into(u16),
725}
726
727/// The client-side result of a right click on an entity (1.8 `doUse`): which interact
728/// packets go out and whether the held item's use follows.
729#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
730pub(crate) enum Interact {
731    /// Neither `interactAt` nor `interact` handled it: both packets, then the item's use.
732    #[default]
733    NotHandled,
734    /// `interactAt` handled it (an armor stand): that packet only.
735    AtHandled,
736    /// `interact` handled it (boats, most minecarts, item frames, leash knots): both
737    /// packets, no item use.
738    Handled,
739    /// 1.16 `interact` answered SUCCESS: both packets and the hand swings, no item use.
740    #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
741    HandledSwing,
742}
743
744/// `Box.method_585` (unnamed in Legacy Yarn): the nearest plane hit of the segment `a → b` on the
745/// box (`x` planes, then `y`, then `z`; ties keep the earlier one).
746fn box_intercept(b: &[f64; 6], a: Vec3, e: Vec3) -> Option<Vec3> {
747    let in_yz = |v: &Vec3| v.y >= b[1] && v.y <= b[4] && v.z >= b[2] && v.z <= b[5];
748    let in_xz = |v: &Vec3| v.x >= b[0] && v.x <= b[3] && v.z >= b[2] && v.z <= b[5];
749    let in_xy = |v: &Vec3| v.x >= b[0] && v.x <= b[3] && v.y >= b[1] && v.y <= b[4];
750    let cands = [
751        intermediate(a, e, 0, b[0]).filter(in_yz),
752        intermediate(a, e, 0, b[3]).filter(in_yz),
753        intermediate(a, e, 1, b[1]).filter(in_xz),
754        intermediate(a, e, 1, b[4]).filter(in_xz),
755        intermediate(a, e, 2, b[2]).filter(in_xy),
756        intermediate(a, e, 2, b[5]).filter(in_xy),
757    ];
758    let mut best: Option<Vec3> = None;
759    for v in cands.into_iter().flatten() {
760        if best.is_none_or(|bv| sq_dist(a, v) < sq_dist(a, bv)) {
761            best = Some(v);
762        }
763    }
764    best
765}
766
767/// Whether the ray from `eyes` along `look` (unit) meets the full cube at `pos` within
768/// `reach`, or starts inside it.
769#[must_use]
770pub(crate) fn ray_hits_cube(eyes: Vec3, look: Vec3, pos: BlockPos, reach: f64) -> bool {
771    let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z));
772    let b = [x, y, z, x + 1.0, y + 1.0, z + 1.0];
773    let inside = eyes.x >= b[0]
774        && eyes.x <= b[3]
775        && eyes.y >= b[1]
776        && eyes.y <= b[4]
777        && eyes.z >= b[2]
778        && eyes.z <= b[5];
779    let end = Vec3::new(
780        eyes.x + look.x * reach,
781        eyes.y + look.y * reach,
782        eyes.z + look.z * reach,
783    );
784    inside || box_intercept(&b, eyes, end).is_some()
785}
786
787/// Mouse buttons held in the world (kept until changed; released by a join or respawn).
788#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
789pub struct Buttons {
790    /// Left: mine / attack.
791    pub left: bool,
792    /// Right: use / place.
793    pub right: bool,
794}
795
796/// A mouse button ([`crate::TickContext::press_preview`]).
797#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
798#[non_exhaustive]
799pub enum Button {
800    /// Left: attack / mine.
801    Left,
802    /// Right: interact / use / place.
803    Right,
804}
805
806/// What a press of a button would act on in this tick's key handling
807/// ([`crate::TickContext::press_preview`]).
808#[derive(Debug, Clone, Copy, PartialEq)]
809#[non_exhaustive]
810pub enum PressOutcome {
811    /// The entity under the crosshair: left attacks it; right sends `use_entity` interact-at
812    /// and interact for it (anticheats check their reach and hitbox like an attack), then
813    /// uses the held item as vanilla does for an entity that does not handle the click.
814    Entity(EntityHit),
815    /// The block under the crosshair: left starts digging it; right clicks it (activates it,
816    /// or the held item goes on it; an item use may still follow).
817    Block(BlockHit),
818    /// Right only: no entity and no block in reach, the held item is used (1.9+: the main
819    /// hand's, else the off hand's).
820    Item,
821    /// Nothing is acted on: left misses (the miss delay), right has no item to use (or the
822    /// player is a spectator, who uses no items).
823    Nothing,
824}
825
826/// What the hands need from the client each tick.
827pub(crate) struct HandsIo<'a> {
828    /// Block lookup (version-specific facts).
829    pub blocks: &'a dyn Fn(i32, i32, i32) -> Option<BlockQuery>,
830    /// The crosshair now.
831    pub target: Option<BlockHit>,
832    /// The held stack's dig / use facts.
833    pub held: Option<HeldItem>,
834    /// The held stack itself (sent with 1.8 placement packets).
835    pub held_stack: Option<ghast_inventory::Stack>,
836    /// The inventory's version (stack identity for block breaking, `breakBlock`'s position).
837    pub inv_version: ghast_inventory::Version,
838    /// Food level (food is only eaten below 20 unless always edible); -1: no food can be
839    /// eaten (1.8 / 1.12 `canConsume` while invulnerable).
840    pub food: i32,
841    /// The off-hand stack's facts (1.9+).
842    pub off_held: Option<HeldItem>,
843    /// The off-hand stack itself.
844    pub off_stack: Option<ghast_inventory::Stack>,
845    /// Mining speed modifiers.
846    pub factors: DigFactors,
847    /// Sneaking (skips block activation when holding an item).
848    pub sneaking: bool,
849    /// The entity the crosshair is on (it wins over `target` when set).
850    pub entity: Option<EntityHit>,
851    /// Packets out (in order).
852    pub out: &'a mut Vec<Outbound>,
853    /// Blocks to predict as air (broken on the client).
854    pub broken: &'a mut Vec<BlockPos>,
855    /// The held stack's count went down by one (a block was placed).
856    pub placed: &'a mut bool,
857    /// Spectator mode: items are never used (vanilla's `useItem` passes without a packet), a
858    /// right click on a block sends the block packet and ends the click there.
859    pub spectator: bool,
860    /// The version's capability row, read only on the paths that need a flag (filling
861    /// per-tick bools from it costs the plain tick): 1.9+ rules (`combat_1_9`: swing after
862    /// the click, both hands tried on right click), the spectator block click's swing
863    /// (`spectator_block_click_swings`: 1.8 – 1.16 swing, 26.x answers CONSUME), 26.3's
864    /// `punch` in place of the attack / dig swing and no use swing on the wire
865    /// (`sends_punch`), its `CHANGE_DESTROY_DIRECTION` (`dig_change_direction`) and the
866    /// 5-tick dig delay after a creative attack (`creative_attack_dig_delay`).
867    pub caps: &'static crate::version::Capabilities,
868    /// Creative mode: a missed attack sets no miss delay (`hasLimitedAttackSpeed` /
869    /// `hasMissTime` is false).
870    pub creative: bool,
871    /// Creative digging: a start packet breaks the block at once, repeated every 5 ticks
872    /// ([`crate::version::Capabilities::creative_instant_dig`]).
873    pub creative_dig: bool,
874    /// 1.8.9 / 1.12.2: the client writes no `block_place` for this click with this block item
875    /// ([`crate::sim::Sim::place_suppressed`]).
876    pub place_blocked: &'a dyn Fn(BlockPos, Face, u16) -> bool,
877    /// The version's oracle-proven rules for a right click on a block (pos, face, the
878    /// cursor as sent) and for a hand's item use in the air (1.9+).
879    pub rules: &'a dyn RightRules,
880}
881
882/// The version's oracle-proven rules of a right click, as the hands ask for them.
883pub(crate) trait RightRules {
884    /// A hand's click on a block (pos, face, the cursor as sent, the off hand?); `None` answers
885    /// keep the hands' own logic.
886    fn place(
887        &self,
888        pos: BlockPos,
889        face: Face,
890        cursor: [f32; 3],
891        off_hand: bool,
892    ) -> crate::sim::predict::PlaceRules;
893    /// A hand's item use in the air (the off hand?), asked after its `use_item` packet;
894    /// [`AirAnswer::Flags`](crate::sim::predict::AirAnswer::Flags) keeps the held-item flags.
895    fn air(&self, off_hand: bool) -> crate::sim::predict::AirAnswer;
896}
897
898/// No rules (no right click this tick, or a version without them).
899pub(crate) struct NoRightRules;
900
901impl RightRules for NoRightRules {
902    fn place(&self, _: BlockPos, _: Face, _: [f32; 3], _: bool) -> crate::sim::predict::PlaceRules {
903        crate::sim::predict::PlaceRules::default()
904    }
905
906    fn air(&self, _: bool) -> crate::sim::predict::AirAnswer {
907        crate::sim::predict::AirAnswer::Flags
908    }
909}
910
911impl HandsIo<'_> {
912    /// The swing of an attack or a dig click (26.3: `punch`).
913    #[inline]
914    fn attack_swing(&mut self) {
915        self.out.push(if self.caps.sends_punch {
916            Outbound::Punch
917        } else {
918            Outbound::Swing
919        });
920    }
921
922    /// The swing of a use (26.3: only the hand animation, no packet).
923    #[inline]
924    fn use_swing(&mut self, off_hand: bool) {
925        if !self.caps.sends_punch {
926            self.out.push(if off_hand {
927                Outbound::SwingOffHand
928            } else {
929                Outbound::Swing
930            });
931        }
932    }
933
934    /// The non-air block at `pos` (`None`: air or not loaded). A block broken earlier in this
935    /// tick (by the behaviour's `dig` or the hands) reads as air, like vanilla, which sets it
936    /// to air in the world at once: the held button must not start it again in the same tick.
937    fn solid(&self, pos: BlockPos) -> Option<BlockQuery> {
938        if self.broken.contains(&pos) {
939            return None;
940        }
941        (self.blocks)(pos.x, pos.y, pos.z).filter(|b| !b.air)
942    }
943}
944
945/// `ClientPlayerInteractionManager` + the `MinecraftClient` click state.
946#[derive(Debug, Clone, Default)]
947pub struct Hands {
948    hitting: bool,
949    current: Option<BlockPos>,
950    damage: f32,
951    /// The main-hand stack of the last start (`selectedStack`).
952    hit_stack: Option<ghast_inventory::Stack>,
953    hit_delay: u32,
954    /// 26.3 `destroyDirection`: the face of the block being dug the server was told (set by a
955    /// start, cleared by a finish; an abort keeps it).
956    destroy_face: Option<Face>,
957    left_click_counter: u32,
958    right_click_delay: u32,
959    using: bool,
960    /// The hand and item id of the use in progress (`getUsedItemHand`, `useItem`).
961    use_hand_off: bool,
962    use_item: u16,
963    /// Player ticks the current use has lasted (`getTicksUsingItem`).
964    use_ticks: u32,
965    /// Counts started uses (the engine tells one use from the next).
966    pub(crate) use_serial: u32,
967    /// This tick's key handling released a use: (off hand, item id, ticks it lasted).
968    released: Option<(bool, u16, u32)>,
969    left_was: bool,
970    right_was: bool,
971    /// This tick's attacks (entity id, the attack-strength ticks before the attack reset
972    /// them); the engine applies their effect on the player before the movement step.
973    pub(crate) attacks: Vec<(i32, u32)>,
974    /// Blocks broken (finish sent).
975    pub broken: u64,
976    /// A dig start / abort / finish was written since the engine last looked (it then tells the
977    /// sim about this tick's dig packets).
978    pub(crate) dug: bool,
979    /// The indices (in the tick's outbound list) of the `block_place` packets that used the
980    /// held block item since the engine last looked (the placed-block prediction).
981    pub(crate) placing: Vec<u32>,
982    /// 1.9+: ticks since the last swing / attack (`ticksSinceLastSwing`, attack cooldown).
983    pub ticks_since_swing: u32,
984    /// The last player tick reset the cooldown after its count (a held item change): the next
985    /// key handling reads 0.
986    pub(crate) cooldown_reset_pending: bool,
987    /// This tick's item use put the stack of this hand (off hand) on: the engine moves it.
988    pub(crate) equipped: Option<bool>,
989    /// Item use steps since the engine last drained them (at most [`MAX_USE_EVENTS`]).
990    pub(crate) use_events: Vec<crate::common::UseEvent>,
991    /// This tick's item use in the air the version's rules decided (off hand, index of its
992    /// `use_item` packet in the tick's outbound list, the use): the engine applies its blocks and
993    /// stack change.
994    pub(crate) air_used: Vec<(bool, u32, crate::sim::predict::AirUse)>,
995}
996
997/// Most item use steps kept between two behaviour ticks.
998const MAX_USE_EVENTS: usize = 64;
999
1000impl Hands {
1001    /// A new player: nothing held, nothing in progress.
1002    pub fn reset(&mut self) {
1003        self.stop_using();
1004        let (broken, dug) = (self.broken, self.dug);
1005        let placing = std::mem::take(&mut self.placing);
1006        let use_events = std::mem::take(&mut self.use_events);
1007        *self = Hands::default();
1008        self.broken = broken;
1009        self.dug = dug;
1010        self.placing = placing;
1011        self.use_events = use_events;
1012    }
1013
1014    /// Records an item use step for the behaviour.
1015    #[cold]
1016    #[inline(never)]
1017    fn use_event(&mut self, e: crate::common::UseEvent) {
1018        if self.use_events.len() < MAX_USE_EVENTS {
1019            self.use_events.push(e);
1020        }
1021    }
1022
1023    /// The use in progress ends: `make` builds its event from (item, off hand, ticks).
1024    #[cold]
1025    #[inline(never)]
1026    fn end_use(&mut self, make: fn(i32, bool, u32) -> crate::common::UseEvent) {
1027        if self.using {
1028            self.using = false;
1029            let e = make(i32::from(self.use_item), self.use_hand_off, self.use_ticks);
1030            self.use_event(e);
1031        }
1032    }
1033
1034    /// The block being broken and its progress 0..1.
1035    #[must_use]
1036    pub fn mining(&self) -> Option<(BlockPos, f32)> {
1037        match (self.hitting, self.current) {
1038            (true, Some(p)) => Some((p, self.damage.min(1.0))),
1039            _ => None,
1040        }
1041    }
1042
1043    /// Using the held item (eating, blocking, drawing a bow).
1044    #[must_use]
1045    pub fn using_item(&self) -> bool {
1046        self.using
1047    }
1048
1049    /// The use in progress: (off hand, item id).
1050    #[must_use]
1051    pub fn use_item(&self) -> Option<(bool, u16)> {
1052        self.using.then_some((self.use_hand_off, self.use_item))
1053    }
1054
1055    /// `startUsingItem`: remembers the hand and the item.
1056    /// Test hook: a use of item `id` in the main hand starts.
1057    #[cfg(test)]
1058    #[allow(dead_code)] // used by the all-version prediction tests
1059    pub(crate) fn test_start_using(&mut self, id: u16) {
1060        self.start_using(false, id);
1061    }
1062
1063    /// The server's living flags started a use of `id` in that hand (1.9+).
1064    pub(crate) fn server_start_using(&mut self, off_hand: bool, id: u16) {
1065        if !self.using {
1066            self.start_using(off_hand, id);
1067        }
1068    }
1069
1070    fn start_using(&mut self, off_hand: bool, id: u16) {
1071        self.use_ticks = 0;
1072        self.using = true;
1073        self.use_serial = self.use_serial.wrapping_add(1);
1074        self.use_hand_off = off_hand;
1075        self.use_item = id;
1076        self.use_event(crate::common::UseEvent::Started {
1077            item: i32::from(id),
1078            off_hand,
1079        });
1080    }
1081
1082    /// The use this tick's key handling released, if any: (off hand, item id, player ticks it
1083    /// lasted).
1084    #[must_use]
1085    pub(crate) fn released_use(&self) -> Option<(bool, u16, u32)> {
1086        self.released
1087    }
1088
1089    /// One player tick of the use in progress (`updatingUsingItem`).
1090    pub(crate) fn count_use_tick(&mut self) {
1091        if self.using {
1092            self.use_ticks = self.use_ticks.saturating_add(1);
1093        }
1094    }
1095
1096    /// The use ends without a release or a finish (the held slot changed, the stack left the
1097    /// hand, a new player entity).
1098    #[inline]
1099    pub fn stop_using(&mut self) {
1100        if self.using {
1101            self.end_use(
1102                |item, off_hand, ticks| crate::common::UseEvent::Interrupted {
1103                    item,
1104                    off_hand,
1105                    ticks,
1106                },
1107            );
1108        }
1109    }
1110
1111    /// The server finished our item use (entity status 9).
1112    pub(crate) fn finish_using(&mut self) {
1113        if self.using {
1114            self.end_use(|item, off_hand, ticks| crate::common::UseEvent::Finished {
1115                item,
1116                off_hand,
1117                ticks,
1118            });
1119        }
1120    }
1121
1122    /// One tick with the buttons as held now.
1123    /// 1.9+ attack strength: `clamp((ticks_since_swing + 0.5) / (20 / attack_speed), 0, 1)`
1124    /// (vanilla `getCooledAttackStrength(0.5F)`; attack speed 4.0 with an empty hand).
1125    #[must_use]
1126    pub fn attack_strength(&self, attack_speed: f64) -> f32 {
1127        attack_strength_at(self.ticks_since_swing, attack_speed)
1128    }
1129
1130    /// `PlayerController.attackEntity`: the attack packet, then `PlayerEntity.attack` (its
1131    /// effect on the player is the engine's, see [`Hands::attacks`]; 1.9+: then the cooldown
1132    /// resets).
1133    pub(crate) fn attack(&mut self, id: i32, io: &mut HandsIo<'_>) {
1134        io.out.push(Outbound::UseEntity {
1135            target: id,
1136            action: crate::common::EntityUse::Attack,
1137            off_hand: false,
1138            sneaking: io.sneaking,
1139        });
1140        if !io.spectator {
1141            self.attacks.push((id, self.ticks_since_swing));
1142        }
1143        self.ticks_since_swing = 0;
1144        if io.caps.creative_attack_dig_delay && io.creative {
1145            self.hit_delay = 5;
1146        }
1147    }
1148
1149    /// Right click on an entity: interact-at then interact.
1150    fn interact(&mut self, e: EntityHit, off_hand: bool, io: &mut HandsIo<'_>) {
1151        self.interact_at(e, off_hand, io);
1152        io.out.push(Outbound::UseEntity {
1153            target: e.id,
1154            action: crate::common::EntityUse::Interact,
1155            off_hand,
1156            sneaking: io.sneaking,
1157        });
1158        // The interaction's stack change on the client (the engine applies it).
1159        let fx = e.interact[usize::from(off_hand)].1;
1160        // The engine applies it to the inventory after the key handling; the rest of this click
1161        // (a fallen-through use) sees the changed stack.
1162        if fx != InteractEffect::None {
1163            let stack = if off_hand {
1164                &mut io.off_stack
1165            } else {
1166                &mut io.held_stack
1167            };
1168            *stack = match (fx, stack.take()) {
1169                (InteractEffect::Damage, Some(st)) => {
1170                    let d = st.damage().saturating_add(1);
1171                    Some(st.with_damage(d))
1172                }
1173                (InteractEffect::Take, Some(st)) => {
1174                    (st.count() > 1).then(|| st.with_count(st.count() - 1))
1175                }
1176                // Handled (no use follows): the inventory change is enough.
1177                (_, st) => st,
1178            };
1179        }
1180    }
1181
1182    /// The interact-at packet (the hit point relative to the entity's position).
1183    fn interact_at(&mut self, e: EntityHit, off_hand: bool, io: &mut HandsIo<'_>) {
1184        let rel = Vec3::new(
1185            e.hit.x - e.entity_pos.x,
1186            e.hit.y - e.entity_pos.y,
1187            e.hit.z - e.entity_pos.z,
1188        );
1189        io.out.push(Outbound::UseEntity {
1190            target: e.id,
1191            action: crate::common::EntityUse::InteractAt(rel),
1192            off_hand,
1193            sneaking: io.sneaking,
1194        });
1195    }
1196
1197    pub(crate) fn tick(&mut self, left: bool, right: bool, io: &mut HandsIo<'_>) {
1198        if self.cooldown_reset_pending {
1199            self.cooldown_reset_pending = false;
1200            self.ticks_since_swing = 0;
1201        } else {
1202            self.ticks_since_swing = self.ticks_since_swing.saturating_add(1);
1203        }
1204        if self.left_click_counter > 0 {
1205            self.left_click_counter -= 1;
1206        }
1207        if self.right_click_delay > 0 {
1208            self.right_click_delay -= 1;
1209        }
1210        let t = io.target;
1211        self.released = None;
1212        if self.using {
1213            if !right {
1214                // releaseUsingItem: the item's releaseUsing (a riptide launch) runs on the client,
1215                // then the packet.
1216                self.released = Some((self.use_hand_off, self.use_item, self.use_ticks));
1217                io.out.push(Outbound::Dig {
1218                    status: DigStatus::ReleaseUseItem,
1219                    pos: BlockPos::new(0, 0, 0),
1220                    face: Face::Down,
1221                });
1222                self.end_use(|item, off_hand, ticks| crate::common::UseEvent::Released {
1223                    item,
1224                    off_hand,
1225                    ticks,
1226                });
1227            }
1228        } else {
1229            if left && !self.left_was {
1230                self.click_mouse(t, io);
1231            }
1232            if right && !self.right_was {
1233                self.right_click_mouse(t, io);
1234            }
1235        }
1236        if right && self.right_click_delay == 0 && !self.using {
1237            self.right_click_mouse(t, io);
1238        }
1239        self.send_click_block_to_controller(left, t, io);
1240        self.left_was = left;
1241        self.right_was = right;
1242        // The player tick that follows (1.16.5 LivingEntity.tickActiveItemStack, 26.1
1243        // updatingUsingItem): the use ends silently once the used hand no longer holds that
1244        // item (a drop, a swap's slot updates). 1.8 / 1.12 compare the stack object, so they
1245        // end it on every slot update of that hand; a changed item is the part modelled.
1246        if self.using {
1247            let hand = if self.use_hand_off {
1248                io.off_held
1249            } else {
1250                io.held
1251            };
1252            if hand.is_none_or(|h| h.id != self.use_item) {
1253                self.stop_using();
1254            }
1255        }
1256    }
1257
1258    fn click_mouse(&mut self, t: Option<BlockHit>, io: &mut HandsIo<'_>) {
1259        if self.left_click_counter > 0 {
1260            return;
1261        }
1262        if let Some(e) = io.entity {
1263            if io.caps.combat_1_9 {
1264                self.attack(e.id, io);
1265                io.attack_swing();
1266            } else {
1267                io.attack_swing();
1268                self.attack(e.id, io);
1269            }
1270            return;
1271        }
1272        if io.caps.combat_1_9 {
1273            // 1.16 MinecraftClient.doAttack: the action, then the swing; a block hit on air falls
1274            // through to the miss case.
1275            match t {
1276                Some(hit) if io.solid(hit.pos).is_some() => {
1277                    self.click_block(hit.pos, hit.face, io);
1278                }
1279                _ => {
1280                    // The miss delay (outside creative); resetCooldown on a miss.
1281                    if !io.creative {
1282                        self.left_click_counter = 10;
1283                    }
1284                    self.ticks_since_swing = 0;
1285                }
1286            }
1287            io.attack_swing();
1288            return;
1289        }
1290        io.attack_swing();
1291        // 1.8 clickMouse: a block hit on air falls through to the miss (the miss delay outside
1292        // creative).
1293        match t {
1294            Some(hit) if io.solid(hit.pos).is_some() => {
1295                self.click_block(hit.pos, hit.face, io);
1296            }
1297            _ if !io.creative => self.left_click_counter = 10,
1298            _ => {}
1299        }
1300    }
1301
1302    fn send_click_block_to_controller(
1303        &mut self,
1304        left: bool,
1305        t: Option<BlockHit>,
1306        io: &mut HandsIo<'_>,
1307    ) {
1308        if !left {
1309            self.left_click_counter = 0;
1310        }
1311        if self.left_click_counter > 0 || self.using {
1312            return;
1313        }
1314        match t.filter(|_| io.entity.is_none()) {
1315            Some(hit) if left => {
1316                let solid = io.solid(hit.pos).is_some();
1317                if solid && self.damage_block(hit.pos, hit.face, io) {
1318                    io.attack_swing();
1319                }
1320            }
1321            _ => self.reset_block_removing(io),
1322        }
1323    }
1324
1325    fn hitting_position(&self, pos: BlockPos, io: &HandsIo<'_>) -> bool {
1326        self.hitting && self.breaking_at(pos, io)
1327    }
1328
1329    /// `isCurrentlyBreaking(pos)`: the block and the stack of the last start (the same item,
1330    /// equal tags / components, the same damage unless the item is damageable), whether or not
1331    /// the breaking was aborted since.
1332    fn breaking_at(&self, pos: BlockPos, io: &HandsIo<'_>) -> bool {
1333        if self.current != Some(pos) {
1334            return false;
1335        }
1336        match (&self.hit_stack, &io.held_stack) {
1337            (None, None) => true,
1338            (Some(was), Some(now)) => {
1339                was.id() == now.id()
1340                    && was.data() == now.data()
1341                    && (now.is_damageable(io.inv_version) || was.damage() == now.damage())
1342            }
1343            _ => false,
1344        }
1345    }
1346
1347    /// Whether a dig start's stack is kept (the drop's in-place change must then follow it).
1348    #[inline]
1349    pub(crate) fn dig_follows_held(&self) -> bool {
1350        self.current.is_some()
1351    }
1352
1353    /// The client changed the held stack in place (26.x and 1.16.5 drop prediction shrinks
1354    /// the stack object): the dig's stack is that object in vanilla (`destroyingItem` /
1355    /// `selectedStack` is the held stack itself, not a copy), so it follows the change and a
1356    /// held button goes on with it; a stack the server's slot update puts there is a new
1357    /// object and does not.
1358    pub(crate) fn held_changed_in_place(
1359        &mut self,
1360        before: Option<&ghast_inventory::Stack>,
1361        after: Option<&ghast_inventory::Stack>,
1362    ) {
1363        if self.hit_stack.as_ref() == before {
1364            self.hit_stack = after.cloned();
1365        }
1366    }
1367
1368    /// `attackBlock`: START (aborting a previous block), instant break when fast enough;
1369    /// creative: START and the block breaks (not by a sword), the next one 5 ticks later. A
1370    /// spectator digs nothing. Whether the click was taken (`attackBlock`'s result).
1371    pub(crate) fn click_block(&mut self, pos: BlockPos, face: Face, io: &mut HandsIo<'_>) -> bool {
1372        if io.creative_dig {
1373            return self.creative_dig(pos, face, io);
1374        }
1375        if io.spectator {
1376            // `shouldLimitWorldModification` / `blockActionRestricted` for a spectator: no packet.
1377            return false;
1378        }
1379        if self.hitting && self.hitting_position(pos, io) {
1380            return true;
1381        }
1382        if self.hitting
1383            && let Some(cur) = self.current
1384        {
1385            io.out.push(Outbound::Dig {
1386                status: DigStatus::Abort,
1387                pos: cur,
1388                face,
1389            });
1390        }
1391        io.out.push(Outbound::Dig {
1392            status: DigStatus::Start,
1393            pos,
1394            face,
1395        });
1396        self.dug = true;
1397        if let Some(b) = io.solid(pos)
1398            && relative_hardness(&b, io.held.as_ref(), io.factors) >= 1.0
1399        {
1400            self.destroyed(pos, io);
1401            return true;
1402        }
1403        self.hitting = true;
1404        self.current = Some(pos);
1405        self.hit_stack.clone_from(&io.held_stack);
1406        self.damage = 0.0;
1407        self.destroy_face = Some(face);
1408        true
1409    }
1410
1411    /// Creative `attackBlock` / `updateBlockBreakingProgress`: START, `breakBlockOrFire`, a
1412    /// 5-tick delay before the next.
1413    #[cold]
1414    #[inline(never)]
1415    fn creative_dig(&mut self, pos: BlockPos, face: Face, io: &mut HandsIo<'_>) -> bool {
1416        io.out.push(Outbound::Dig {
1417            status: DigStatus::Start,
1418            pos,
1419            face,
1420        });
1421        self.dug = true;
1422        if !io.held.is_some_and(|h| h.creative_keeps_blocks) && io.solid(pos).is_some() {
1423            self.destroyed(pos, io);
1424        }
1425        self.hit_delay = 5;
1426        true
1427    }
1428
1429    /// `updateBlockBreakingProgress`.
1430    fn damage_block(&mut self, pos: BlockPos, face: Face, io: &mut HandsIo<'_>) -> bool {
1431        if self.hit_delay > 0 {
1432            self.hit_delay -= 1;
1433            return true;
1434        }
1435        if io.creative_dig {
1436            return self.creative_dig(pos, face, io);
1437        }
1438        // A held button back on the last start's block goes on silently, even after an abort.
1439        if !self.breaking_at(pos, io) {
1440            return self.click_block(pos, face, io);
1441        }
1442        let Some(b) = io.solid(pos) else {
1443            self.hitting = false;
1444            return false;
1445        };
1446        self.damage += relative_hardness(&b, io.held.as_ref(), io.factors);
1447        if self.damage >= 1.0 {
1448            self.hitting = false;
1449            io.out.push(Outbound::Dig {
1450                status: DigStatus::Finish,
1451                pos,
1452                face,
1453            });
1454            self.dug = true;
1455            self.destroyed(pos, io);
1456            self.destroy_face = None;
1457            self.damage = 0.0;
1458            self.hit_delay = 5;
1459        } else if io.caps.dig_change_direction && self.destroy_face != Some(face) {
1460            // 26.3 continueDestroyBlock: the crosshair on another face of the same block.
1461            self.destroy_face = Some(face);
1462            io.out.push(Outbound::Dig {
1463                status: DigStatus::ChangeDirection,
1464                pos,
1465                face,
1466            });
1467        }
1468        true
1469    }
1470
1471    /// `breakBlock`: air on the client; 1.8 / 1.12 move the last start's block to y = −1
1472    /// (1.16.5 keeps it: a held button on a block set back there goes on silently).
1473    fn destroyed(&mut self, pos: BlockPos, io: &mut HandsIo<'_>) {
1474        io.broken.push(pos);
1475        if matches!(
1476            io.inv_version,
1477            ghast_inventory::Version::V1_8 | ghast_inventory::Version::V1_12
1478        ) && let Some(c) = self.current
1479        {
1480            self.current = Some(BlockPos::new(c.x, -1, c.z));
1481        }
1482        self.broken += 1;
1483    }
1484
1485    /// 26.3 `MultiPlayerGameMode.stopDestroyBlock` outside the key handling (a server
1486    /// teleport): the abort of the block being dug, the progress gone, the attack strength
1487    /// reset. Nothing while no block is being dug.
1488    pub(crate) fn stop_destroy_block(&mut self, out: &mut Vec<Outbound>) {
1489        if !self.hitting {
1490            return;
1491        }
1492        if let Some(cur) = self.current {
1493            out.push(Outbound::Dig {
1494                status: DigStatus::Abort,
1495                pos: cur,
1496                face: Face::Down,
1497            });
1498            self.dug = true;
1499        }
1500        self.hitting = false;
1501        self.damage = 0.0;
1502        self.ticks_since_swing = 0;
1503    }
1504
1505    /// `cancelBlockBreaking`.
1506    pub(crate) fn reset_block_removing(&mut self, io: &mut HandsIo<'_>) {
1507        if !self.hitting {
1508            return;
1509        }
1510        if let Some(cur) = self.current {
1511            io.out.push(Outbound::Dig {
1512                status: DigStatus::Abort,
1513                pos: cur,
1514                face: Face::Down,
1515            });
1516            self.dug = true;
1517        }
1518        self.hitting = false;
1519        self.damage = 0.0;
1520    }
1521
1522    /// `doUse` (nothing while a block is being hit).
1523    fn right_click_mouse(&mut self, t: Option<BlockHit>, io: &mut HandsIo<'_>) {
1524        if self.hitting {
1525            return;
1526        }
1527        self.right_click_delay = 4;
1528        if io.caps.combat_1_9 {
1529            self.right_click_modern(t, io);
1530            return;
1531        }
1532        if let Some(e) = io.entity {
1533            // 1.8: interact-at, interact; not handled -> the item is used.
1534            if e.interact[0].0 == Interact::AtHandled {
1535                self.interact_at(e, false, io);
1536                return;
1537            }
1538            self.interact(e, false, io);
1539            if e.interact[0].0 == Interact::Handled {
1540                return;
1541            }
1542            if let Some(h) = io.held.filter(|_| !io.spectator) {
1543                io.out.push(Outbound::UseItem {
1544                    held: io.held_stack.clone(),
1545                    off_hand: false,
1546                });
1547                self.used_legacy(h, io);
1548            }
1549            return;
1550        }
1551        let mut fall_through = true;
1552        if let Some(hit) = t
1553            && let Some(b) = io.solid(hit.pos)
1554        {
1555            if self.right_click_block(hit, &b, io) {
1556                fall_through = false;
1557                io.use_swing(false);
1558            }
1559            if io.held.is_none() {
1560                return;
1561            }
1562        }
1563        if fall_through
1564            && !io.spectator
1565            && let Some(h) = io.held
1566        {
1567            // interactItem: the item itself (position -1, face 255).
1568            io.out.push(Outbound::UseItem {
1569                held: io.held_stack.clone(),
1570                off_hand: false,
1571            });
1572            self.used_legacy(h, io);
1573        }
1574    }
1575
1576    /// 1.8 `interactItem` after its packet: the item's `onStartUse`, by the version's rules
1577    /// (`RightRules::air`: the use started, the fishing rod's swing, the blocks and the hand's
1578    /// stack) or the held-item flags (food only when the player can eat; armor goes on).
1579    fn used_legacy(&mut self, h: HeldItem, io: &mut HandsIo<'_>) {
1580        if let crate::sim::predict::AirAnswer::Known(a) = io.rules.air(false) {
1581            let k = io.out.len() as u32 - 1;
1582            if a.starts {
1583                self.start_using(false, h.id);
1584            }
1585            if a.result == crate::sim::predict::AirResult::Success {
1586                io.use_swing(false);
1587            }
1588            if !matches!(a.hand, crate::sim::predict::HandChange::Keep)
1589                || a.blocks.as_ref().is_some_and(|b| !b.is_empty())
1590            {
1591                self.air_used.push((false, k, a));
1592            }
1593            return;
1594        }
1595        if h.usable && (!h.food || (io.food >= 0 && (h.always_edible || io.food < 20))) {
1596            self.start_using(false, h.id);
1597        } else if h.equips {
1598            self.equipped = Some(false);
1599        }
1600    }
1601
1602    /// 1.9+ `doItemUse` (1.16.5 Yarn): main hand, then off hand; per hand the block (activation, then
1603    /// the item on the block), then the item itself; the first success / consume ends it.
1604    fn right_click_modern(&mut self, t: Option<BlockHit>, io: &mut HandsIo<'_>) {
1605        let any_item = io.held.is_some() || io.off_held.is_some();
1606        // the off hand's turn is predicted only after a main hand the rules decided
1607        let mut main_decided = true;
1608        for off_hand in [false, true] {
1609            let (held, stack) = if off_hand {
1610                (io.off_held, io.off_stack.clone())
1611            } else {
1612                (io.held, io.held_stack.clone())
1613            };
1614            if let Some(e) = io.entity {
1615                match e.interact[usize::from(off_hand)].0 {
1616                    Interact::AtHandled => {
1617                        self.interact_at(e, off_hand, io);
1618                        return;
1619                    }
1620                    Interact::Handled => {
1621                        self.interact(e, off_hand, io);
1622                        return;
1623                    }
1624                    Interact::HandledSwing => {
1625                        self.interact(e, off_hand, io);
1626                        io.use_swing(off_hand);
1627                        return;
1628                    }
1629                    Interact::NotHandled => self.interact(e, off_hand, io),
1630                }
1631            } else if let Some(hit) = t
1632                && let Some(b) = io.solid(hit.pos)
1633                && let rules = if off_hand && !main_decided {
1634                    crate::sim::predict::PlaceRules::default()
1635                } else {
1636                    io.rules.place(
1637                        hit.pos,
1638                        hit.face,
1639                        [
1640                            (hit.hit.x - f64::from(hit.pos.x)) as f32,
1641                            (hit.hit.y - f64::from(hit.pos.y)) as f32,
1642                            (hit.hit.z - f64::from(hit.pos.z)) as f32,
1643                        ],
1644                        off_hand,
1645                    )
1646                }
1647                && {
1648                    if !off_hand {
1649                        main_decided = rules.block_packet.is_some()
1650                            && rules.used.is_some()
1651                            && !rules.air_use_unknown;
1652                    }
1653                    true
1654                }
1655                // 1.12 interactBlock: FAIL without a packet when the block item cannot go
1656                // there (not for spectators or an activated block); the item use follows.
1657                && rules.block_packet.unwrap_or_else(|| {
1658                    !(!io.spectator
1659                        && !(b.activates && !(io.sneaking && any_item))
1660                        && held.is_some_and(|h| (io.place_blocked)(hit.pos, hit.face, h.id)))
1661                })
1662            {
1663                let cursor = Vec3::new(
1664                    hit.hit.x - f64::from(hit.pos.x),
1665                    hit.hit.y - f64::from(hit.pos.y),
1666                    hit.hit.z - f64::from(hit.pos.z),
1667                );
1668                io.out.push(if hit.distance <= INSIDE_HIT {
1669                    // the ray started inside the block (1.14+ wire)
1670                    Outbound::PlaceInside {
1671                        pos: hit.pos,
1672                        face: hit.face,
1673                        cursor,
1674                        held: stack.clone(),
1675                        off_hand,
1676                    }
1677                } else {
1678                    Outbound::Place {
1679                        pos: hit.pos,
1680                        face: hit.face,
1681                        cursor,
1682                        held: stack.clone(),
1683                        off_hand,
1684                    }
1685                });
1686                // interactBlock / useItemOn of a spectator: the packet, then SUCCESS (1.12, 1.16:
1687                // swing) or CONSUME (26.x: no swing); the click ends (no off hand, no item use).
1688                if io.spectator {
1689                    if io.caps.spectator_block_click_swings {
1690                        io.use_swing(off_hand);
1691                    }
1692                    return;
1693                }
1694                // the version's rules: SUCCESS (swing; what the item sets is `Sim::place_sent`)
1695                // or not (the item use follows)
1696                if let Some(used) = rules.used {
1697                    if used {
1698                        if rules.starts_use
1699                            && let Some(h) = held
1700                        {
1701                            // eaten instead of placed (nothing set on the client)
1702                            self.start_using(off_hand, h.id);
1703                            return;
1704                        }
1705                        if held.is_some() {
1706                            if !off_hand {
1707                                *io.placed = true;
1708                            }
1709                            self.placing.push(io.out.len() as u32 - 1);
1710                        }
1711                        if !rules.no_swing {
1712                            io.use_swing(off_hand);
1713                        }
1714                        return;
1715                    }
1716                    if rules.ends {
1717                        return;
1718                    }
1719                } else if b.activates && !(io.sneaking && any_item) {
1720                    // Sneaking with something in either hand skips the block's activation.
1721                    io.use_swing(off_hand);
1722                    return;
1723                }
1724                if rules.used.is_none()
1725                    && let Some(h) = held
1726                    && h.places_block
1727                    && h.count > 0
1728                {
1729                    if !off_hand {
1730                        *io.placed = true;
1731                    }
1732                    // an off-hand placement after an undecided main hand: not predicted
1733                    if !off_hand || main_decided {
1734                        self.placing.push(io.out.len() as u32 - 1);
1735                    }
1736                    io.use_swing(off_hand);
1737                    return;
1738                }
1739            }
1740            if let Some(h) = held.filter(|_| !io.spectator) {
1741                let k = io.out.len() as u32;
1742                io.out.push(Outbound::UseItem {
1743                    held: stack,
1744                    off_hand,
1745                });
1746                match io.rules.air(off_hand) {
1747                    crate::sim::predict::AirAnswer::Known(a) => {
1748                        use crate::sim::predict::AirResult;
1749                        if a.starts {
1750                            self.start_using(off_hand, h.id);
1751                        }
1752                        let result = a.result;
1753                        // (the off hand's changes after an undecided main hand: not predicted)
1754                        if (!off_hand || main_decided)
1755                            && (!matches!(a.hand, crate::sim::predict::HandChange::Keep)
1756                                || a.blocks.as_ref().is_none_or(|b| !b.is_empty()))
1757                        {
1758                            self.air_used.push((off_hand, k, a));
1759                        }
1760                        if result == AirResult::Pass {
1761                            continue;
1762                        }
1763                        if result == AirResult::Success {
1764                            io.use_swing(off_hand);
1765                        }
1766                        return;
1767                    }
1768                    // the off hand's turn after a use not modelled: not predicted
1769                    crate::sim::predict::AirAnswer::Unknown => {
1770                        if !off_hand {
1771                            main_decided = false;
1772                        }
1773                    }
1774                    crate::sim::predict::AirAnswer::Flags => {}
1775                }
1776                if h.swing_on_use {
1777                    // InteractionResult.SUCCESS with a client swing: the use ends here.
1778                    io.use_swing(off_hand);
1779                    return;
1780                }
1781                if h.use_succeeds {
1782                    // 1.12 SUCCESS without a swing (thrown items, the fishing rod).
1783                    return;
1784                }
1785                if h.usable {
1786                    if !h.food || (io.food >= 0 && (h.always_edible || io.food < 20)) {
1787                        self.start_using(off_hand, h.id);
1788                        return;
1789                    }
1790                } else if h.equips {
1791                    // ArmorItem / ElytraItem.use, 26.x Equippable.swapWithEquipmentSlot:
1792                    // SUCCESS (1.16.5 / 26.x swing on the client), the click ends.
1793                    self.equipped = Some(off_hand);
1794                    if h.equip_swings {
1795                        io.use_swing(off_hand);
1796                    }
1797                    return;
1798                }
1799            }
1800        }
1801    }
1802
1803    /// `onRightClick`: the placement packet; returns whether something was activated or
1804    /// placed (the caller swings).
1805    pub(crate) fn right_click_block(
1806        &mut self,
1807        hit: BlockHit,
1808        b: &BlockQuery,
1809        io: &mut HandsIo<'_>,
1810    ) -> bool {
1811        let cursor = Vec3::new(
1812            f64::from((hit.hit.x - f64::from(hit.pos.x)) as f32),
1813            f64::from((hit.hit.y - f64::from(hit.pos.y)) as f32),
1814            f64::from((hit.hit.z - f64::from(hit.pos.z)) as f32),
1815        );
1816        let activated = b.activates && (!io.sneaking || io.held.is_none());
1817        let rules = io.rules.place(
1818            hit.pos,
1819            hit.face,
1820            [cursor.x as f32, cursor.y as f32, cursor.z as f32],
1821            false,
1822        );
1823        // 1.8 onRightClick: no packet when the block item cannot go there (false: the caller
1824        // uses the item itself).
1825        let blocked = match rules.block_packet {
1826            Some(send) => !send,
1827            None => {
1828                !io.spectator
1829                    && !activated
1830                    && io
1831                        .held
1832                        .is_some_and(|h| (io.place_blocked)(hit.pos, hit.face, h.id))
1833            }
1834        };
1835        if blocked {
1836            return false;
1837        }
1838        io.out.push(Outbound::Place {
1839            pos: hit.pos,
1840            face: hit.face,
1841            cursor,
1842            held: io.held_stack.clone(),
1843            off_hand: false,
1844        });
1845        // 1.8 onRightClick: a spectator's click ends with the packet (true: the caller swings).
1846        if io.spectator {
1847            return true;
1848        }
1849        if let Some(used) = rules.used {
1850            // the rules also predict what the item sets on the client (`Sim::place_sent`)
1851            if used && io.held.is_some() {
1852                *io.placed = true;
1853                self.placing.push(io.out.len() as u32 - 1);
1854            }
1855            return used;
1856        }
1857        if activated {
1858            return true;
1859        }
1860        match io.held {
1861            Some(h) if h.places_block && h.count > 0 => {
1862                *io.placed = true;
1863                self.placing.push(io.out.len() as u32 - 1);
1864                true
1865            }
1866            _ => false,
1867        }
1868    }
1869}
1870
1871#[cfg(test)]
1872mod tests {
1873
1874    /// The 1.8.9 capability row with the 1.9+ rules and the spectator click swing as given.
1875    fn test_caps(modern: bool, swings: bool) -> &'static crate::version::Capabilities {
1876        Box::leak(Box::new(crate::version::Capabilities {
1877            combat_1_9: modern,
1878            spectator_block_click_swings: swings,
1879            ..*crate::version::GameVersion::V1_8_9.caps()
1880        }))
1881    }
1882    use super::*;
1883
1884    fn stone() -> BlockQuery {
1885        BlockQuery {
1886            exact: None,
1887            air: false,
1888            water: false,
1889            block: 1,
1890            hardness: 1.5,
1891            dig_material: Some(DigMaterial::Rock),
1892            harvest_tools: &[270, 274],
1893            selection: Some([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]),
1894            stairs: None,
1895            activates: false,
1896        }
1897    }
1898
1899    #[test]
1900    fn hand_stone_time() {
1901        // Stone by hand, on ground: 1 / 1.5 / 100 per tick; the f32 sum (as vanilla's
1902        // currentBreakingProgress) reaches 1 on the 151st tick, not the 150th.
1903        let f = DigFactors {
1904            on_ground: true,
1905            ..DigFactors::default()
1906        };
1907        let per_tick = relative_hardness(&stone(), None, f);
1908        let mut d = 0.0_f32;
1909        let mut n = 0;
1910        while d < 1.0 {
1911            d += per_tick;
1912            n += 1;
1913        }
1914        assert_eq!(n, 151);
1915    }
1916
1917    #[test]
1918    fn look_south_hits_block() {
1919        let look = look_vector(0.0, 0.0);
1920        assert!(look.z > 0.99 && look.x.abs() < 1e-3);
1921        let blocks = |x: i32, y: i32, z: i32| {
1922            Some(if (x, y, z) == (0, 1, 2) {
1923                stone()
1924            } else {
1925                BlockQuery {
1926                    air: true,
1927                    selection: None,
1928                    ..stone()
1929                }
1930            })
1931        };
1932        let hit = pick(&blocks, Vec3::new(0.5, 1.62, 0.5), look, REACH).unwrap();
1933        assert_eq!(hit.pos, BlockPos::new(0, 1, 2));
1934        assert_eq!(hit.face, Face::North);
1935        assert!((hit.distance - 1.5).abs() < 1e-3);
1936    }
1937
1938    fn io_blocks(x: i32, y: i32, z: i32) -> Option<BlockQuery> {
1939        Some(if (x, y, z) == (0, 0, 0) {
1940            stone()
1941        } else {
1942            BlockQuery {
1943                air: true,
1944                selection: None,
1945                ..stone()
1946            }
1947        })
1948    }
1949
1950    fn kinds(out: &[Outbound]) -> Vec<&'static str> {
1951        out.iter()
1952            .map(|o| match o {
1953                Outbound::Place {
1954                    off_hand: false, ..
1955                }
1956                | Outbound::PlaceInside {
1957                    off_hand: false, ..
1958                } => "place_main",
1959                Outbound::Place { off_hand: true, .. }
1960                | Outbound::PlaceInside { off_hand: true, .. } => "place_off",
1961                Outbound::UseItem {
1962                    off_hand: false, ..
1963                } => "use_main",
1964                Outbound::UseItem { off_hand: true, .. } => "use_off",
1965                Outbound::Swing => "swing",
1966                Outbound::SwingOffHand => "swing_off",
1967                Outbound::Dig { .. } => "dig",
1968                _ => "other",
1969            })
1970            .collect()
1971    }
1972
1973    /// The miss delay: a left press on air outside creative (`hasLimitedAttackSpeed`) holds
1974    /// the button off the block for 10 ticks (the counter counts down at the start of the
1975    /// tick); creative digs at once. 1.8 and 1.9+ alike; releasing the button clears it.
1976    #[test]
1977    fn air_swing_miss_delay_outside_creative() {
1978        let hit = Some(BlockHit {
1979            pos: BlockPos::new(0, 0, 0),
1980            face: Face::Up,
1981            hit: Vec3::new(0.5, 1.0, 0.5),
1982            distance: 1.6,
1983        });
1984        for modern in [false, true] {
1985            for creative in [false, true] {
1986                let mut h = Hands::default();
1987                let mut first_dig = None;
1988                for t in 0..20u32 {
1989                    let (mut out, mut broken, mut placed) = (Vec::new(), Vec::new(), false);
1990                    let mut io = HandsIo {
1991                        blocks: &io_blocks,
1992                        target: if t == 0 { None } else { hit },
1993                        held: None,
1994                        held_stack: None,
1995                        inv_version: ghast_inventory::Version::V1_8,
1996                        food: 20,
1997                        off_held: None,
1998                        off_stack: None,
1999                        entity: None,
2000                        factors: DigFactors::default(),
2001                        sneaking: false,
2002                        out: &mut out,
2003                        broken: &mut broken,
2004                        placed: &mut placed,
2005                        spectator: false,
2006                        caps: test_caps(modern, true),
2007                        creative,
2008                        creative_dig: creative,
2009                        place_blocked: &|_, _, _| false,
2010                        rules: &NoRightRules,
2011                    };
2012                    h.tick(true, false, &mut io);
2013                    if t == 0 {
2014                        assert_eq!(kinds(&out), ["swing"], "{modern} {creative}");
2015                    }
2016                    if first_dig.is_none() && kinds(&out).contains(&"dig") {
2017                        first_dig = Some(t);
2018                    }
2019                }
2020                let want = if creative { 1 } else { 10 };
2021                assert_eq!(first_dig, Some(want), "modern {modern} creative {creative}");
2022            }
2023        }
2024    }
2025
2026    /// 1.16 right click: empty hands try both hands on the block; a block item places with
2027    /// the main hand and swings.
2028    #[test]
2029    fn modern_right_click_hands() {
2030        let hit = Some(BlockHit {
2031            pos: BlockPos::new(0, 0, 0),
2032            face: Face::Up,
2033            hit: Vec3::new(0.5, 1.0, 0.5),
2034            distance: 1.6,
2035        });
2036        let run = |held: Option<HeldItem>| {
2037            let mut h = Hands::default();
2038            let (mut out, mut broken, mut placed) = (Vec::new(), Vec::new(), false);
2039            let mut io = HandsIo {
2040                blocks: &io_blocks,
2041                target: hit,
2042                held,
2043                held_stack: None,
2044                inv_version: ghast_inventory::Version::V1_8,
2045                food: 20,
2046                off_held: None,
2047                off_stack: None,
2048                entity: None,
2049                factors: DigFactors::default(),
2050                sneaking: false,
2051                out: &mut out,
2052                broken: &mut broken,
2053                placed: &mut placed,
2054                spectator: false,
2055                caps: test_caps(true, true),
2056                creative: false,
2057                creative_dig: false,
2058                place_blocked: &|_, _, _| false,
2059                rules: &NoRightRules,
2060            };
2061            h.tick(false, true, &mut io);
2062            kinds(&out)
2063        };
2064        assert_eq!(run(None), ["place_main", "place_off"]);
2065        let dirt = HeldItem {
2066            id: 3,
2067            count: 10,
2068            places_block: true,
2069            ..HeldItem::default()
2070        };
2071        assert_eq!(run(Some(dirt)), ["place_main", "swing"]);
2072        // An item that is neither a block nor usable: place on the block, then use it.
2073        let stick = HeldItem {
2074            id: 280,
2075            count: 1,
2076            ..HeldItem::default()
2077        };
2078        assert_eq!(run(Some(stick)), ["place_main", "use_main", "place_off"]);
2079    }
2080
2081    /// 1.8.9 / 1.12.2: a block item that cannot go there writes no block packet; the item
2082    /// itself is used instead (1.8 `doUse` falls through to `interactItem`; 1.12 `FAIL` goes on
2083    /// to `use_item`, then the off hand).
2084    #[test]
2085    fn unplaceable_block_item_sends_no_block_packet() {
2086        let hit = Some(BlockHit {
2087            pos: BlockPos::new(0, 0, 0),
2088            face: Face::Up,
2089            hit: Vec3::new(0.5, 1.0, 0.5),
2090            distance: 1.6,
2091        });
2092        let dirt = HeldItem {
2093            id: 3,
2094            count: 10,
2095            places_block: true,
2096            ..HeldItem::default()
2097        };
2098        let run = |modern: bool, blocked: bool| {
2099            let mut h = Hands::default();
2100            let (mut out, mut broken, mut placed) = (Vec::new(), Vec::new(), false);
2101            let check = move |_: BlockPos, _: Face, id: u16| blocked && id == 3;
2102            let mut io = HandsIo {
2103                blocks: &io_blocks,
2104                target: hit,
2105                held: Some(dirt),
2106                held_stack: None,
2107                inv_version: ghast_inventory::Version::V1_8,
2108                food: 20,
2109                off_held: None,
2110                off_stack: None,
2111                entity: None,
2112                factors: DigFactors::default(),
2113                sneaking: false,
2114                out: &mut out,
2115                broken: &mut broken,
2116                placed: &mut placed,
2117                spectator: false,
2118                caps: test_caps(modern, true),
2119                creative: false,
2120                creative_dig: false,
2121                place_blocked: &check,
2122                rules: &NoRightRules,
2123            };
2124            h.tick(false, true, &mut io);
2125            assert_eq!(placed, !blocked);
2126            assert_eq!(h.placing.is_empty(), blocked);
2127            kinds(&out)
2128        };
2129        assert_eq!(run(false, false), ["place_main", "swing"]);
2130        assert_eq!(run(false, true), ["use_main"]);
2131        assert_eq!(run(true, false), ["place_main", "swing"]);
2132        assert_eq!(run(true, true), ["use_main", "place_off"]);
2133    }
2134
2135    /// A spectator's right click on a block: the block packet, then the click ends (no
2136    /// placement, no off hand, no item use); 1.8 – 1.16 swing, 26.x (CONSUME) does not. The
2137    /// block item is never recorded for the placed-block prediction.
2138    #[test]
2139    fn spectator_block_click_ends_with_the_packet() {
2140        let hit = Some(BlockHit {
2141            pos: BlockPos::new(0, 0, 0),
2142            face: Face::Up,
2143            hit: Vec3::new(0.5, 1.0, 0.5),
2144            distance: 1.6,
2145        });
2146        let dirt = HeldItem {
2147            id: 3,
2148            count: 10,
2149            places_block: true,
2150            ..HeldItem::default()
2151        };
2152        let run = |modern: bool, swings: bool, held: Option<HeldItem>| {
2153            let mut h = Hands::default();
2154            let (mut out, mut broken, mut placed) = (Vec::new(), Vec::new(), false);
2155            let mut io = HandsIo {
2156                blocks: &io_blocks,
2157                target: hit,
2158                held,
2159                held_stack: None,
2160                inv_version: ghast_inventory::Version::V1_8,
2161                food: 20,
2162                off_held: None,
2163                off_stack: None,
2164                entity: None,
2165                factors: DigFactors::default(),
2166                sneaking: false,
2167                out: &mut out,
2168                broken: &mut broken,
2169                placed: &mut placed,
2170                spectator: true,
2171                caps: test_caps(modern, swings),
2172                creative: false,
2173                creative_dig: false,
2174                place_blocked: &|_, _, _| true,
2175                rules: &NoRightRules,
2176            };
2177            h.tick(false, true, &mut io);
2178            assert!(!placed);
2179            assert!(h.placing.is_empty());
2180            kinds(&out)
2181        };
2182        for held in [None, Some(dirt)] {
2183            // 1.8 onRightClick true: swing, no item use.
2184            assert_eq!(run(false, true, held), ["place_main", "swing"]);
2185            // 1.12 / 1.16 SUCCESS: main hand only, swing.
2186            assert_eq!(run(true, true, held), ["place_main", "swing"]);
2187            // 26.x CONSUME: main hand only, no swing.
2188            assert_eq!(run(true, false, held), ["place_main"]);
2189        }
2190    }
2191
2192    /// Pressing the left button on an instant-break block sends one START: the held-button
2193    /// pass of the same tick sees the block as air (vanilla breaks it in the world at once),
2194    /// for 1.8 and 1.16 alike. Also with a block the behaviour broke earlier in the tick.
2195    #[test]
2196    fn instant_break_press_starts_once() {
2197        fn instant(x: i32, y: i32, z: i32) -> Option<BlockQuery> {
2198            Some(if (x, y, z) == (0, 0, 0) {
2199                BlockQuery {
2200                    hardness: 0.0,
2201                    ..stone()
2202                }
2203            } else {
2204                BlockQuery {
2205                    air: true,
2206                    selection: None,
2207                    ..stone()
2208                }
2209            })
2210        }
2211        let hit = Some(BlockHit {
2212            pos: BlockPos::new(0, 0, 0),
2213            face: Face::Up,
2214            hit: Vec3::new(0.5, 1.0, 0.5),
2215            distance: 1.6,
2216        });
2217        for modern in [false, true] {
2218            for pre_broken in [false, true] {
2219                let mut h = Hands::default();
2220                let (mut out, mut placed) = (Vec::new(), false);
2221                let mut broken = if pre_broken {
2222                    vec![BlockPos::new(0, 0, 0)]
2223                } else {
2224                    Vec::new()
2225                };
2226                let mut io = HandsIo {
2227                    blocks: &instant,
2228                    target: hit,
2229                    held: None,
2230                    held_stack: None,
2231                    inv_version: ghast_inventory::Version::V1_8,
2232                    food: 20,
2233                    off_held: None,
2234                    off_stack: None,
2235                    entity: None,
2236                    factors: DigFactors::default(),
2237                    sneaking: false,
2238                    out: &mut out,
2239                    broken: &mut broken,
2240                    placed: &mut placed,
2241                    spectator: false,
2242                    caps: test_caps(modern, true),
2243                    creative: false,
2244                    creative_dig: false,
2245                    place_blocked: &|_, _, _| false,
2246                    rules: &NoRightRules,
2247                };
2248                h.tick(true, false, &mut io);
2249                let starts = out
2250                    .iter()
2251                    .filter(|o| {
2252                        matches!(
2253                            o,
2254                            Outbound::Dig {
2255                                status: DigStatus::Start,
2256                                ..
2257                            }
2258                        )
2259                    })
2260                    .count();
2261                let want = usize::from(!pre_broken);
2262                assert_eq!(
2263                    starts, want,
2264                    "modern {modern} pre_broken {pre_broken}: {out:?}"
2265                );
2266                assert_eq!(h.broken, want as u64);
2267            }
2268        }
2269    }
2270
2271    /// 1.16 left click: block_dig start, then the swing (1.8: swing first).
2272    #[test]
2273    fn modern_left_click_order() {
2274        let hit = Some(BlockHit {
2275            pos: BlockPos::new(0, 0, 0),
2276            face: Face::Up,
2277            hit: Vec3::new(0.5, 1.0, 0.5),
2278            distance: 1.6,
2279        });
2280        for (modern, want) in [(true, ["dig", "swing"]), (false, ["swing", "dig"])] {
2281            let mut h = Hands::default();
2282            let (mut out, mut broken, mut placed) = (Vec::new(), Vec::new(), false);
2283            let mut io = HandsIo {
2284                blocks: &io_blocks,
2285                target: hit,
2286                held: None,
2287                held_stack: None,
2288                inv_version: ghast_inventory::Version::V1_8,
2289                food: 20,
2290                off_held: None,
2291                off_stack: None,
2292                entity: None,
2293                factors: DigFactors::default(),
2294                sneaking: false,
2295                out: &mut out,
2296                broken: &mut broken,
2297                placed: &mut placed,
2298                spectator: false,
2299                caps: test_caps(modern, true),
2300                creative: false,
2301                creative_dig: false,
2302                place_blocked: &|_, _, _| false,
2303                rules: &NoRightRules,
2304            };
2305            h.click_mouse(hit, &mut io);
2306            assert_eq!(kinds(&out)[..2], want);
2307        }
2308    }
2309
2310    #[test]
2311    fn dig_sequence() {
2312        let blocks = |x: i32, y: i32, z: i32| {
2313            Some(if (x, y, z) == (0, 0, 0) {
2314                BlockQuery {
2315                    hardness: 0.6,
2316                    ..stone()
2317                }
2318            } else {
2319                BlockQuery {
2320                    air: true,
2321                    selection: None,
2322                    ..stone()
2323                }
2324            })
2325        };
2326        let target = Some(BlockHit {
2327            pos: BlockPos::new(0, 0, 0),
2328            face: Face::Up,
2329            hit: Vec3::new(0.5, 1.0, 0.5),
2330            distance: 1.6,
2331        });
2332        let mut h = Hands::default();
2333        let mut out = Vec::new();
2334        let mut broken = Vec::new();
2335        let mut placed = false;
2336        let mut ticks = 0;
2337        while broken.is_empty() && ticks < 200 {
2338            let mut io = HandsIo {
2339                blocks: &blocks,
2340                target,
2341                held: None,
2342                held_stack: None,
2343                inv_version: ghast_inventory::Version::V1_8,
2344                food: 20,
2345                off_held: None,
2346                off_stack: None,
2347                entity: None,
2348                factors: DigFactors {
2349                    on_ground: true,
2350                    ..DigFactors::default()
2351                },
2352                sneaking: false,
2353                out: &mut out,
2354                broken: &mut broken,
2355                placed: &mut placed,
2356                spectator: false,
2357                caps: test_caps(false, true),
2358                creative: false,
2359                creative_dig: false,
2360                place_blocked: &|_, _, _| false,
2361                rules: &NoRightRules,
2362            };
2363            h.tick(true, false, &mut io);
2364            ticks += 1;
2365        }
2366        // 0.6 hardness, not harvestable by hand: 1/0.6/100 per tick; the f32 sum reaches 1 on
2367        // the 61st tick (damage is added from the START tick on).
2368        assert_eq!(broken, [BlockPos::new(0, 0, 0)]);
2369        let digs: Vec<_> = out
2370            .iter()
2371            .filter_map(|o| match o {
2372                Outbound::Dig { status, .. } => Some(*status),
2373                _ => None,
2374            })
2375            .collect();
2376        assert_eq!(digs, [DigStatus::Start, DigStatus::Finish]);
2377        assert_eq!(ticks, 61);
2378        // The click swings, and every damage tick swings (two on the first tick).
2379        assert_eq!(
2380            out.iter().filter(|o| matches!(o, Outbound::Swing)).count(),
2381            62
2382        );
2383    }
2384}