1use ghast_data::DigMaterial;
27use ghast_protocol::BlockPos;
28
29use crate::common::{DigStatus, Face, Outbound, Vec3};
30
31pub const REACH: f64 = 4.5;
33
34#[derive(Debug, Clone, Copy, PartialEq)]
36#[non_exhaustive]
37pub struct BlockQuery {
38 pub air: bool,
40 pub water: bool,
42 pub block: u16,
44 pub hardness: f32,
46 pub dig_material: Option<DigMaterial>,
48 pub harvest_tools: &'static [u16],
50 pub selection: Option<[f64; 6]>,
52 pub stairs: Option<[Option<[f64; 6]>; 8]>,
55 pub activates: bool,
57 pub(crate) exact: Option<ExactDig>,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq)]
64pub(crate) enum ExactDig {
65 #[cfg(feature = "v1_8")]
67 V1_8,
68 #[cfg(feature = "v1_12_2")]
70 V1_12,
71 #[cfg(feature = "v1_16_5")]
73 V1_16_5,
74 #[cfg(feature = "v26_1")]
76 V26_1(ModernDig),
77 #[cfg(feature = "v26_2")]
79 V26_2(ModernDig),
80 #[cfg(feature = "v26_3")]
82 V26_3(ModernDig),
83}
84
85#[cfg(ghast_modern)]
87#[derive(Debug, Clone, Copy, PartialEq)]
88pub(crate) struct ModernDig {
89 pub(crate) state: u16,
91 pub(crate) mining_efficiency: f64,
93 pub(crate) block_break_speed: f64,
95 pub(crate) submerged_mining_speed: f64,
97 pub(crate) conduit_power: Option<i32>,
99}
100
101pub(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#[derive(Debug, Clone, Copy, Default)]
110#[non_exhaustive]
111pub struct HeldItem {
112 pub id: u16,
114 pub count: u8,
116 pub efficiency: u8,
118 pub places_block: bool,
120 pub usable: bool,
122 pub food: bool,
124 pub always_edible: bool,
126 pub tool_speed: Option<fn(DigMaterial, u16) -> f32>,
128 #[cfg_attr(not(ghast_modern), allow(dead_code))]
130 pub(crate) modern_item: Option<u16>,
131 pub(crate) swing_on_use: bool,
134 pub(crate) equips: bool,
137 pub(crate) equip_swings: bool,
139 pub(crate) creative_keeps_blocks: bool,
142 pub(crate) use_succeeds: bool,
145}
146
147impl BlockQuery {
148 #[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 pub const AIR: BlockQuery = BlockQuery::new(0).with_air(true);
168
169 #[must_use]
171 pub const fn with_air(mut self, on: bool) -> Self {
172 self.air = on;
173 self
174 }
175
176 #[must_use]
178 pub const fn with_water(mut self, on: bool) -> Self {
179 self.water = on;
180 self
181 }
182
183 #[must_use]
185 pub const fn with_hardness(mut self, hardness: f32) -> Self {
186 self.hardness = hardness;
187 self
188 }
189
190 #[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 #[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 #[must_use]
206 pub const fn with_selection(mut self, b: Option<[f64; 6]>) -> Self {
207 self.selection = b;
208 self
209 }
210
211 #[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 #[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 #[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 #[must_use]
250 pub const fn with_count(mut self, count: u8) -> Self {
251 self.count = count;
252 self
253 }
254
255 #[must_use]
257 pub const fn with_efficiency(mut self, level: u8) -> Self {
258 self.efficiency = level;
259 self
260 }
261
262 #[must_use]
264 pub const fn with_places_block(mut self, on: bool) -> Self {
265 self.places_block = on;
266 self
267 }
268
269 #[must_use]
271 pub const fn with_usable(mut self, on: bool) -> Self {
272 self.usable = on;
273 self
274 }
275
276 #[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 #[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 #[must_use]
295 pub const fn with_on_ground(mut self, on: bool) -> Self {
296 self.on_ground = on;
297 self
298 }
299
300 #[must_use]
302 pub const fn with_in_water(mut self, on: bool) -> Self {
303 self.in_water = on;
304 self
305 }
306
307 #[must_use]
309 pub const fn with_aqua_affinity(mut self, on: bool) -> Self {
310 self.aqua_affinity = on;
311 self
312 }
313
314 #[must_use]
316 pub const fn with_haste(mut self, level: u8) -> Self {
317 self.haste = level;
318 self
319 }
320
321 #[must_use]
323 pub const fn with_fatigue(mut self, level: u8) -> Self {
324 self.fatigue = level;
325 self
326 }
327}
328
329#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
331#[non_exhaustive]
332pub struct DigFactors {
333 pub on_ground: bool,
335 pub in_water: bool,
337 pub aqua_affinity: bool,
339 pub haste: u8,
341 pub fatigue: u8,
343}
344
345fn 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, &, 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#[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 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#[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#[derive(Debug, Clone, Copy, PartialEq)]
463#[non_exhaustive]
464pub struct BlockHit {
465 pub pos: BlockPos,
467 pub face: Face,
469 pub hit: Vec3,
471 pub distance: f64,
473}
474
475const INSIDE_HIT: f64 = 0.0051;
479
480fn floor(v: f64) -> i32 {
482 let i = v as i32;
483 if v < f64::from(i) { i - 1 } else { i }
484}
485
486fn 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
505fn 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#[derive(Debug, Clone, Copy, PartialEq)]
536#[non_exhaustive]
537pub enum RayResult {
538 Block(BlockHit),
540 Miss {
543 pos: BlockPos,
545 face: Face,
547 hit: Vec3,
549 },
550 None,
552}
553
554pub 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 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 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#[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#[derive(Debug, Clone, Copy, PartialEq)]
689#[non_exhaustive]
690pub struct EntityHit {
691 pub id: i32,
693 pub hit: Vec3,
695 pub entity_pos: Vec3,
697 pub distance: f64,
699 pub(crate) interact: [(Interact, InteractEffect); 2],
702}
703
704#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
706#[cfg_attr(not(any(feature = "v1_8", feature = "v1_12_2")), allow(dead_code))]
708pub(crate) enum InteractEffect {
709 #[default]
711 None,
712 Take,
714 Damage,
716 IntoMilk,
718 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
730pub(crate) enum Interact {
731 #[default]
733 NotHandled,
734 AtHandled,
736 Handled,
739 #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
741 HandledSwing,
742}
743
744fn 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
789pub struct Buttons {
790 pub left: bool,
792 pub right: bool,
794}
795
796#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
798#[non_exhaustive]
799pub enum Button {
800 Left,
802 Right,
804}
805
806#[derive(Debug, Clone, Copy, PartialEq)]
809#[non_exhaustive]
810pub enum PressOutcome {
811 Entity(EntityHit),
815 Block(BlockHit),
818 Item,
821 Nothing,
824}
825
826pub(crate) struct HandsIo<'a> {
828 pub blocks: &'a dyn Fn(i32, i32, i32) -> Option<BlockQuery>,
830 pub target: Option<BlockHit>,
832 pub held: Option<HeldItem>,
834 pub held_stack: Option<ghast_inventory::Stack>,
836 pub inv_version: ghast_inventory::Version,
838 pub food: i32,
841 pub off_held: Option<HeldItem>,
843 pub off_stack: Option<ghast_inventory::Stack>,
845 pub factors: DigFactors,
847 pub sneaking: bool,
849 pub entity: Option<EntityHit>,
851 pub out: &'a mut Vec<Outbound>,
853 pub broken: &'a mut Vec<BlockPos>,
855 pub placed: &'a mut bool,
857 pub spectator: bool,
860 pub caps: &'static crate::version::Capabilities,
868 pub creative: bool,
871 pub creative_dig: bool,
874 pub place_blocked: &'a dyn Fn(BlockPos, Face, u16) -> bool,
877 pub rules: &'a dyn RightRules,
880}
881
882pub(crate) trait RightRules {
884 fn place(
887 &self,
888 pos: BlockPos,
889 face: Face,
890 cursor: [f32; 3],
891 off_hand: bool,
892 ) -> crate::sim::predict::PlaceRules;
893 fn air(&self, off_hand: bool) -> crate::sim::predict::AirAnswer;
896}
897
898pub(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 #[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 #[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 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#[derive(Debug, Clone, Default)]
947pub struct Hands {
948 hitting: bool,
949 current: Option<BlockPos>,
950 damage: f32,
951 hit_stack: Option<ghast_inventory::Stack>,
953 hit_delay: u32,
954 destroy_face: Option<Face>,
957 left_click_counter: u32,
958 right_click_delay: u32,
959 using: bool,
960 use_hand_off: bool,
962 use_item: u16,
963 use_ticks: u32,
965 pub(crate) use_serial: u32,
967 released: Option<(bool, u16, u32)>,
969 left_was: bool,
970 right_was: bool,
971 pub(crate) attacks: Vec<(i32, u32)>,
974 pub broken: u64,
976 pub(crate) dug: bool,
979 pub(crate) placing: Vec<u32>,
982 pub ticks_since_swing: u32,
984 pub(crate) cooldown_reset_pending: bool,
987 pub(crate) equipped: Option<bool>,
989 pub(crate) use_events: Vec<crate::common::UseEvent>,
991 pub(crate) air_used: Vec<(bool, u32, crate::sim::predict::AirUse)>,
995}
996
997const MAX_USE_EVENTS: usize = 64;
999
1000impl Hands {
1001 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 #[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 #[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 #[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 #[must_use]
1045 pub fn using_item(&self) -> bool {
1046 self.using
1047 }
1048
1049 #[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 #[cfg(test)]
1058 #[allow(dead_code)] pub(crate) fn test_start_using(&mut self, id: u16) {
1060 self.start_using(false, id);
1061 }
1062
1063 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 #[must_use]
1085 pub(crate) fn released_use(&self) -> Option<(bool, u16, u32)> {
1086 self.released
1087 }
1088
1089 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 #[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 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 #[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 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 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 let fx = e.interact[usize::from(off_hand)].1;
1160 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 (_, st) => st,
1178 };
1179 }
1180 }
1181
1182 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 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 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 match t {
1276 Some(hit) if io.solid(hit.pos).is_some() => {
1277 self.click_block(hit.pos, hit.face, io);
1278 }
1279 _ => {
1280 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 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 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 #[inline]
1349 pub(crate) fn dig_follows_held(&self) -> bool {
1350 self.current.is_some()
1351 }
1352
1353 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 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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 && 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 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 if io.spectator {
1689 if io.caps.spectator_block_click_swings {
1690 io.use_swing(off_hand);
1691 }
1692 return;
1693 }
1694 if let Some(used) = rules.used {
1697 if used {
1698 if rules.starts_use
1699 && let Some(h) = held
1700 {
1701 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 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 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 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 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 io.use_swing(off_hand);
1779 return;
1780 }
1781 if h.use_succeeds {
1782 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 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 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 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 if io.spectator {
1847 return true;
1848 }
1849 if let Some(used) = rules.used {
1850 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 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 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 #[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 #[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 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 #[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 #[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 assert_eq!(run(false, true, held), ["place_main", "swing"]);
2185 assert_eq!(run(true, true, held), ["place_main", "swing"]);
2187 assert_eq!(run(true, false, held), ["place_main"]);
2189 }
2190 }
2191
2192 #[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 #[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 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 assert_eq!(
2380 out.iter().filter(|o| matches!(o, Outbound::Swing)).count(),
2381 62
2382 );
2383 }
2384}