use std::sync::atomic::{AtomicI16, Ordering};
use ghast_data::v1_12::item_use::{UseClass, arrow, use_class};
use ghast_data::v1_12::{BlockState, MaterialKind};
use ghast_physics::math::Aabb;
use ghast_physics::pick::v1_12 as pick;
use ghast_protocol::BlockPos;
use ghast_protocol::nbt::{Compound, NamedTag, RawNbt, Tag};
use super::predict::{AirAnswer, AirQuery, AirResult, AirUse, HandChange};
use crate::common::GameMode;
pub(crate) struct Ctx<'a> {
pub world: &'a ghast_world::v1_12::World,
pub bb: Aabb,
pub climbing: bool,
pub fall_flying: bool,
pub nether: bool,
pub entities: Option<&'a ghast_entity::Entities>,
pub own_id: i32,
pub maps: &'a AtomicI16,
}
const BUCKET: i32 = 325;
const WATER_BUCKET: i32 = 326;
const LAVA_BUCKET: i32 = 327;
const POTION: i32 = 373;
const FILLED_MAP: i32 = 358;
const PASS: AirResult = AirResult::Pass;
const DONE: AirResult = AirResult::Consume;
fn known(result: AirResult, starts: bool) -> AirAnswer {
AirAnswer::Known(AirUse {
result,
starts,
blocks: Some(Vec::new()),
hand: HandChange::Keep,
})
}
fn offset(p: BlockPos, face: u8) -> BlockPos {
let [x, y, z] = [p.x, p.y, p.z];
match face {
0 => BlockPos::new(x, y - 1, z),
1 => BlockPos::new(x, y + 1, z),
2 => BlockPos::new(x, y, z - 1),
3 => BlockPos::new(x, y, z + 1),
4 => BlockPos::new(x - 1, y, z),
_ => BlockPos::new(x + 1, y, z),
}
}
fn state(w: &ghast_world::v1_12::World, p: BlockPos) -> BlockState {
let valid = (0..256).contains(&p.y)
&& (-30_000_000..30_000_000).contains(&p.x)
&& (-30_000_000..30_000_000).contains(&p.z);
if !valid {
return BlockState::AIR;
}
w.block_state(p.x, p.y, p.z).unwrap_or(BlockState::AIR)
}
fn replaceable(w: &ghast_world::v1_12::World, p: BlockPos) -> bool {
let s = state(w, p);
match s.block().id() {
78 => s.meta() == 0,
175 => {
let lower = if s.meta() & 8 != 0 {
let b = state(w, offset(p, 0));
if b.block().id() == 175 { b.meta() } else { 0 }
} else {
s.meta()
};
matches!(lower & 7, 2 | 3)
}
_ => s.block().material().replaceable,
}
}
fn with_tag(id: i32, key: &str, value: Tag) -> ghast_inventory::Stack {
let nbt = RawNbt::from_named(&NamedTag {
name: String::new(),
tag: Tag::Compound(Compound(vec![(key.to_owned(), value)])),
})
.ok();
ghast_inventory::Stack::new(id, 1, 0).with_nbt(nbt)
}
fn may_not_modify(q: &AirQuery<'_>) -> Option<bool> {
if matches!(q.game_mode, GameMode::Survival | GameMode::Creative) {
Some(false)
} else if q.stack.nbt().is_some() {
None
} else {
Some(true)
}
}
pub(crate) fn air_use(cx: &Ctx<'_>, q: &AirQuery<'_>) -> AirAnswer {
let Some(class) = u16::try_from(q.stack.id()).ok().and_then(use_class) else {
return AirAnswer::Unknown;
};
let n = |v: f64| if v == 0.0 { 0.0 } else { v };
let eye = [n(q.eyes.x), n(q.eyes.y), n(q.eyes.z)];
let look = pick::look_vector(q.yaw, q.pitch);
let ray = |liquids: bool| pick::item_ray(cx.world, eye, look, liquids);
let creative = q.creative;
match class {
UseClass::Plain
| UseClass::Food
| UseClass::Armor
| UseClass::Elytra
| UseClass::Thrown
| UseClass::OnAStick
| UseClass::MilkBucket
| UseClass::Drink
| UseClass::Shield => AirAnswer::Flags,
UseClass::FishingRod => known(AirResult::Success, false),
UseClass::SpawnEgg => known(PASS, false),
UseClass::EnderPearl => AirAnswer::Known(AirUse {
result: DONE,
starts: false,
blocks: Some(Vec::new()),
hand: if creative {
HandChange::Keep
} else {
HandChange::UseOne
},
}),
UseClass::Firework => known(if cx.fall_flying { DONE } else { PASS }, false),
UseClass::WritableBook | UseClass::WrittenBook => known(DONE, false),
UseClass::KnowledgeBook => {
let tag = q.stack.nbt().and_then(|r| r.parse().ok()).flatten();
let recipes = tag.is_some_and(|t| match t.tag {
Tag::Compound(c) => matches!(c.get("Recipes"), Some(Tag::List(_))),
_ => false,
});
AirAnswer::Known(AirUse {
result: if recipes { DONE } else { PASS },
starts: false,
blocks: Some(Vec::new()),
hand: if creative {
HandChange::Keep
} else {
HandChange::Empty
},
})
}
UseClass::EmptyMap => {
let id = cx.maps.fetch_add(1, Ordering::Relaxed);
AirAnswer::Known(AirUse {
result: DONE,
starts: false,
blocks: Some(Vec::new()),
hand: HandChange::ExchangeLegacy {
output: ghast_inventory::Stack::new(FILLED_MAP, 1, id),
},
})
}
UseClass::Bow => {
let ammo = creative || has_arrow(q.inv);
known(if ammo { DONE } else { PASS }, ammo)
}
UseClass::EnderEye => {
let frame = ray(false).is_some_and(|h| {
h.is_block() && state(cx.world, pos_of(h.pos)).block().id() == 120
});
if frame {
known(PASS, false)
} else {
known(DONE, true)
}
}
UseClass::GlassBottle => glass_bottle(cx, q, ray(true)),
UseClass::LilyPad => lily_pad(cx, q, ray(true)),
UseClass::Boat => boat(cx, q, eye, look),
UseClass::Bucket => bucket(cx, q, &ray),
_ => AirAnswer::Unknown,
}
}
fn pos_of(p: [i32; 3]) -> BlockPos {
BlockPos::new(p[0], p[1], p[2])
}
fn has_arrow(inv: &ghast_inventory::Inventory) -> bool {
(0..41).any(|k| {
inv.player(k)
.is_some_and(|s| u16::try_from(s.id()).is_ok_and(arrow))
})
}
fn glass_bottle(
cx: &Ctx<'_>,
q: &AirQuery<'_>,
hit: Option<ghast_physics::pick::BlockHit>,
) -> AirAnswer {
if let Some(ents) = cx.entities
&& ents
.iter()
.any(|e| matches!(e.entity_type(), ghast_entity::EntityType::LegacyObject(3)))
{
return AirAnswer::Unknown;
}
let Some(hit) = hit.filter(ghast_physics::pick::BlockHit::is_block) else {
return known(PASS, false);
};
match may_not_modify(q) {
None => return AirAnswer::Unknown,
Some(true) => return known(PASS, false),
Some(false) => {}
}
let at = state(cx.world, pos_of(hit.pos));
if at.block().material().kind != MaterialKind::Water {
return known(PASS, false);
}
AirAnswer::Known(AirUse {
result: DONE,
starts: false,
blocks: Some(Vec::new()),
hand: HandChange::ExchangeLegacy {
output: with_tag(POTION, "Potion", Tag::String("minecraft:water".into())),
},
})
}
fn lily_pad(
cx: &Ctx<'_>,
q: &AirQuery<'_>,
hit: Option<ghast_physics::pick::BlockHit>,
) -> AirAnswer {
let Some(hit) = hit else {
return known(PASS, false);
};
if !hit.is_block() {
return known(PASS, false);
}
match may_not_modify(q) {
None => return AirAnswer::Unknown,
Some(true) => return known(PASS, false),
Some(false) => {}
}
let pos = pos_of(hit.pos);
let at = state(cx.world, pos);
let above = offset(pos, 1);
let still_water = at.block().material().kind == MaterialKind::Water && at.meta() == 0;
if !(still_water && state(cx.world, above).block().material().kind == MaterialKind::Air) {
return known(PASS, false);
}
let blocks = if (0..256).contains(&above.y) {
vec![(
above,
u32::from(ghast_data::v1_12::Block::WATERLILY.default_state().raw()),
)]
} else {
Vec::new()
};
AirAnswer::Known(AirUse {
result: DONE,
starts: false,
blocks: Some(blocks),
hand: if q.creative {
HandChange::Keep
} else {
HandChange::UseOne
},
})
}
fn boat(cx: &Ctx<'_>, q: &AirQuery<'_>, eye: [f64; 3], look: [f64; 3]) -> AirAnswer {
let Some(hit) = pick::item_ray(cx.world, eye, look, true) else {
return known(PASS, false);
};
if let Some(ents) = cx.entities {
let near = ents.iter().any(|e| {
e.id() != cx.own_id
&& e.bounding_box().is_none_or(|b| {
b[3] > eye[0] - 7.0
&& b[0] < eye[0] + 7.0
&& b[4] > eye[1] - 7.0
&& b[1] < eye[1] + 7.0
&& b[5] > eye[2] - 7.0
&& b[2] < eye[2] + 7.0
})
});
if near {
return AirAnswer::Unknown;
}
}
if !hit.is_block() {
return known(PASS, false);
}
let water = matches!(state(cx.world, pos_of(hit.pos)).block().id(), 8 | 9);
let at = [
hit.location[0],
if water {
hit.location[1] - 0.12
} else {
hit.location[1]
},
hit.location[2],
];
let me: &[Aabb] = if cx.climbing {
&[]
} else {
std::slice::from_ref(&cx.bb)
};
if !ghast_physics::v1_12::boat_item_fits(cx.world, at, me) {
return known(PASS, false);
}
AirAnswer::Known(AirUse {
result: DONE,
starts: false,
blocks: Some(Vec::new()),
hand: if q.creative {
HandChange::Keep
} else {
HandChange::UseOne
},
})
}
fn bucket(
cx: &Ctx<'_>,
q: &AirQuery<'_>,
ray: &dyn Fn(bool) -> Option<ghast_physics::pick::BlockHit>,
) -> AirAnswer {
let empty = q.stack.id() == BUCKET;
let Some(hit) = ray(empty).filter(ghast_physics::pick::BlockHit::is_block) else {
return known(PASS, false);
};
match may_not_modify(q) {
None => return AirAnswer::Unknown,
Some(true) => return known(PASS, false),
Some(false) => {}
}
let w = cx.world;
let pos = pos_of(hit.pos);
let face = hit.face as u8;
if empty {
let at = state(w, pos);
let filled = match at.block().material().kind {
MaterialKind::Water if at.meta() == 0 => WATER_BUCKET,
MaterialKind::Lava if at.meta() == 0 => LAVA_BUCKET,
_ => return known(PASS, false),
};
return AirAnswer::Known(AirUse {
result: DONE,
starts: false,
blocks: Some(vec![(pos, u32::from(BlockState::AIR.raw()))]),
hand: if q.creative {
HandChange::Keep
} else {
HandChange::ExchangeLegacy {
output: ghast_inventory::Stack::new(filled, 1, 0),
}
},
});
}
let target = if replaceable(w, pos) && face == 1 {
pos
} else {
offset(pos, face)
};
let s = state(w, target);
let m = s.block().material();
if !(m.kind == MaterialKind::Air || !m.solid || replaceable(w, target)) {
return known(PASS, false);
}
let water = q.stack.id() == WATER_BUCKET;
let blocks = if (cx.nether && water) || !(0..256).contains(&target.y) {
Vec::new()
} else {
let placed = if water {
ghast_data::v1_12::Block::FLOWING_WATER
} else {
ghast_data::v1_12::Block::FLOWING_LAVA
}
.default_state();
if placed == s {
Vec::new()
} else {
vec![(target, u32::from(placed.raw()))]
}
};
AirAnswer::Known(AirUse {
result: DONE,
starts: false,
blocks: Some(blocks),
hand: if q.creative {
HandChange::Keep
} else {
HandChange::Replace(ghast_inventory::Stack::new(BUCKET, 1, 0))
},
})
}