use ghast_data::v1_16_5::{Block, BlockState, Property};
use super::blocks::{Shape, collision_shape};
use super::piston_shapes::SOURCE_SHAPES;
use super::player::{PlayerState, PlayerStepCtx, piston_move, tick_with_moving};
use super::{PlayerExt, Surroundings};
use crate::input::{Packets, TickInput};
use crate::math::{Aabb, BoxOps, sorted_box};
use crate::voxel::{Points, VoxelShape};
use crate::world::{BlockView, WorldBorder};
pub type Facing = u8;
const PUSH_LIMIT: usize = 12;
const CLIENT_HOLD: u8 = 5;
#[inline]
#[must_use]
pub const fn offset(f: Facing) -> [i32; 3] {
match f {
0 => [0, -1, 0],
1 => [0, 1, 0],
2 => [0, 0, -1],
3 => [0, 0, 1],
4 => [-1, 0, 0],
_ => [1, 0, 0],
}
}
#[inline]
const fn opposite(f: Facing) -> Facing {
f ^ 1
}
#[inline]
const fn axis(f: Facing) -> u8 {
f >> 1
}
#[inline]
const fn axis_index(f: Facing) -> usize {
[1, 2, 0][(f >> 1) as usize]
}
#[inline]
fn step(p: [i32; 3], f: Facing, n: i32) -> [i32; 3] {
let o = offset(f);
[p[0] + o[0] * n, p[1] + o[1] * n, p[2] + o[2] * n]
}
const FACING_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
#[must_use]
pub fn follows_neighbours(b: Block) -> bool {
const SHAPED: [&str; 10] = [
"north", "east", "south", "west", "up", "down", "shape", "in_wall", "snowy", "type",
];
let name = b.name();
name.ends_with("_carpet")
|| name == "snow"
|| name.ends_with("rail")
|| b.properties().any(|d| {
let n = d.property.name();
SHAPED.contains(&n) && (n != "type" || d.values.contains(&"left"))
})
}
#[must_use]
pub fn edits_need_shape_updates<W: BlockView<State = BlockState>>(
world: &W,
edits: &[([i32; 3], BlockState)],
) -> bool {
let v = Layered { w: world, edits };
edits.iter().any(|&(p, s)| {
follows_neighbours(s.block())
|| (0..6).any(|f| {
let q = step(p, f, 1);
follows_neighbours(v.block(q[0], q[1], q[2]).block())
})
})
}
fn prop(name: &str) -> Property {
Property::from_name(name).expect("1.16.5 property")
}
fn facing_of(s: BlockState) -> Option<Facing> {
let v = s.get(prop("facing"))?;
FACING_NAMES
.iter()
.position(|n| *n == v)
.map(|i| i as Facing)
}
fn with(s: BlockState, p: &str, v: &str) -> BlockState {
s.with(prop(p), v).expect("1.16.5 state property")
}
fn is_piston(b: Block) -> bool {
b == Block::PISTON || b == Block::STICKY_PISTON
}
fn is_sticky_block(b: Block) -> bool {
b == Block::SLIME_BLOCK || b == Block::HONEY_BLOCK
}
fn stuck(a: Block, b: Block) -> bool {
if (a == Block::HONEY_BLOCK && b == Block::SLIME_BLOCK)
|| (a == Block::SLIME_BLOCK && b == Block::HONEY_BLOCK)
{
return false;
}
is_sticky_block(a) || is_sticky_block(b)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Behaviour {
Normal,
Destroy,
Block,
PushOnly,
}
fn behaviour(id: u16) -> Behaviour {
match id {
19..=24
| 26..=27
| 59..=64
| 75..=90
| 94..=99
| 119..=133
| 141..=144
| 148
| 152
| 161..=162
| 171..=179
| 181..=184
| 187
| 189
| 192
| 198..=199
| 202..=205
| 244..=249
| 254
| 258
| 265
| 267
| 271..=272
| 281..=325
| 330..=332
| 410..=415
| 485..=489
| 491..=492
| 497
| 507
| 509..=525
| 574..=575
| 577
| 593..=597
| 603..=607
| 613..=618
| 621..=623
| 626
| 666
| 677..=679
| 682
| 688
| 690..=691
| 697
| 699..=703
| 708..=709
| 718..=721
| 738..=741
| 757..=758 => Behaviour::Destroy,
93 | 100..=101 | 118 | 201 | 262 | 326..=328 | 378 | 499 | 673 | 742 => Behaviour::Block,
526..=541 => Behaviour::PushOnly,
_ => Behaviour::Normal,
}
}
fn unbreakable(id: u16) -> bool {
matches!(
id,
25 | 118 | 201 | 262..=263 | 277 | 378 | 499..=501 | 726..=727
)
}
fn has_block_entity(id: u16) -> bool {
matches!(
id,
70 | 75..=90
| 118
| 145
| 147
| 154..=160
| 165..=170
| 190
| 259..=260
| 262
| 270
| 277..=278
| 314..=325
| 329
| 332..=333
| 336
| 342
| 416..=447
| 499..=501
| 509..=525
| 620
| 668..=670
| 674
| 677
| 680..=681
| 722..=727
| 730..=731
)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MovingBlock {
pub pos: [i32; 3],
pub pushed: BlockState,
pub facing: Facing,
pub extending: bool,
pub source: bool,
pub progress: f32,
pub last_progress: f32,
pub hold: u8,
removed: bool,
}
impl MovingBlock {
fn moves(&self) -> Facing {
if self.extending {
self.facing
} else {
opposite(self.facing)
}
}
fn shift(&self, p: f32) -> f32 {
if self.extending { p - 1.0 } else { 1.0 - p }
}
fn head_state(&self) -> BlockState {
if !self.extending && self.source && is_piston(self.pushed.block()) {
let f = facing_of(self.pushed).unwrap_or(self.facing);
let mut h = with(
Block::PISTON_HEAD.default_state(),
"facing",
FACING_NAMES[f as usize],
);
h = with(
h,
"short",
if self.progress > 0.25 {
"true"
} else {
"false"
},
);
if self.pushed.block() == Block::STICKY_PISTON {
h = with(h, "type", "sticky");
}
h
} else {
self.pushed
}
}
}
pub type Edits = Vec<([i32; 3], BlockState)>;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Pistons {
blocks: Vec<MovingBlock>,
delta: [f64; 3],
delta_time: i64,
}
impl Pistons {
#[must_use]
pub const fn new() -> Pistons {
Pistons {
blocks: Vec::new(),
delta: [0.0; 3],
delta_time: 0,
}
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.blocks.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &MovingBlock> {
self.blocks.iter().filter(|b| !b.removed)
}
#[must_use]
pub fn touches(&self, bb: &Aabb) -> bool {
self.iter().any(|m| {
bb.intersects(&Aabb::new(
f64::from(m.pos[0]) - 1.0,
f64::from(m.pos[1]) - 1.0,
f64::from(m.pos[2]) - 1.0,
f64::from(m.pos[0]) + 2.0,
f64::from(m.pos[1]) + 2.0,
f64::from(m.pos[2]) + 2.0,
))
})
}
#[must_use]
pub fn untracked_near(&self, bb: &Aabb) -> bool {
let area = bb.grow(1.0, 1.0, 1.0);
self.iter().any(|m| {
let n = m.pushed.block().name();
(n.ends_with("_stairs") || n.ends_with("_trapdoor"))
&& area.intersects(&Aabb::new(
f64::from(m.pos[0]) - 1.0,
f64::from(m.pos[1]) - 1.0,
f64::from(m.pos[2]) - 1.0,
f64::from(m.pos[0]) + 2.0,
f64::from(m.pos[1]) + 2.0,
f64::from(m.pos[2]) + 2.0,
))
})
}
#[must_use]
pub fn at(&self, pos: [i32; 3]) -> Option<&MovingBlock> {
self.blocks.iter().find(|b| !b.removed && b.pos == pos)
}
fn index_at(&self, pos: [i32; 3]) -> Option<usize> {
self.blocks.iter().position(|b| !b.removed && b.pos == pos)
}
pub fn clear(&mut self) {
self.blocks.clear();
}
pub fn reset_player(&mut self) {
self.delta = [0.0; 3];
self.delta_time = 0;
}
pub fn retain(&mut self, mut keep: impl FnMut(&MovingBlock) -> bool) {
self.blocks.retain(|b| !b.removed && keep(b));
}
pub fn block_changed(&mut self, pos: [i32; 3], old: BlockState, new: BlockState) {
if old.block() == Block::MOVING_PISTON
&& new.block() != Block::MOVING_PISTON
&& let Some(i) = self.index_at(pos)
{
self.blocks.remove(i);
}
}
pub fn chunk_replaced(&mut self, cx: i32, cz: i32) {
self.blocks
.retain(|b| !(b.pos[0] >> 4 == cx && b.pos[2] >> 4 == cz));
}
fn add(&mut self, mut b: MovingBlock) {
if let Some(i) = self.index_at(b.pos) {
self.blocks[i].removed = true;
}
b.removed = false;
self.blocks.push(b);
}
fn drop_removed(&mut self) {
self.blocks.retain(|b| !b.removed);
}
pub fn block_event<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
pos: [i32; 3],
action: u8,
data: u8,
edits: &mut Edits,
) -> bool {
let start = edits.len();
let mut ov = Overlay {
w: world,
edits,
start,
pistons: self,
};
let r = ov.on_event(pos, action, data);
self.drop_removed();
r
}
pub fn tick_blocks<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
tick_moving(None, world, time, self, edits);
}
}
}
#[derive(Default)]
pub(crate) struct MovingShapes {
shapes: Vec<([i32; 3], Placed)>,
}
#[derive(Clone, Copy)]
enum Placed {
Owned(OwnedShape),
Static(VoxelShape<'static>, bool),
}
#[derive(Clone, Copy)]
struct OwnedShape {
simple: Option<[u32; 3]>,
pts: [[f64; 2]; 3],
cells: [u64; 8],
full: bool,
}
impl OwnedShape {
fn view(&self) -> VoxelShape<'_> {
let axes = match self.simple {
Some(n) => [
Points::Fractional(n[0]),
Points::Fractional(n[1]),
Points::Fractional(n[2]),
],
None => [
Points::Explicit(&self.pts[0]),
Points::Explicit(&self.pts[1]),
Points::Explicit(&self.pts[2]),
],
};
VoxelShape {
axes,
cells: &self.cells,
}
}
fn cuboid(b: &Aabb) -> Option<OwnedShape> {
let (x0, y0, z0, x1, y1, z1) = (b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z);
let res = |lo: f64, hi: f64| -> Option<u32> {
if lo < -1.0e-7 || hi > 1.000_000_1 {
return None;
}
(0..=3).find(|&i| {
let k = f64::from(1u32 << i);
let (d, e) = (lo * k, hi * k);
(d - d.floor()).abs() < 1.0e-7 && (e - e.floor()).abs() < 1.0e-7
})
};
let mut s = OwnedShape {
simple: None,
pts: [[x0, x1], [y0, y1], [z0, z1]],
cells: [0; 8],
full: false,
};
match (res(x0, x1), res(y0, y1), res(z0, z1)) {
(Some(0), Some(0), Some(0)) => {
let inside =
0.5 >= x0 && 0.5 < x1 && 0.5 >= y0 && 0.5 < y1 && 0.5 >= z0 && 0.5 < z1;
if !inside {
return None;
}
s.simple = Some([1, 1, 1]);
s.cells[0] = 1;
s.full = true;
}
(Some(i), Some(j), Some(k)) => {
let (l, m, n) = (1u32 << i, 1u32 << j, 1u32 << k);
let r = |v: f64, k: u32| (v * f64::from(k)).round() as i64;
let (o, p) = (r(x0, l), r(x1, l));
let (q, rr) = (r(y0, m), r(y1, m));
let (t, u) = (r(z0, n), r(z1, n));
s.simple = Some([l, m, n]);
for x in o..p {
for y in q..rr {
for z in t..u {
let idx = ((x as u32 * m + y as u32) * n + z as u32) as usize;
s.cells[idx / 64] |= 1 << (idx % 64);
}
}
}
}
_ => s.cells[0] = 1,
}
Some(s)
}
}
impl MovingShapes {
pub(crate) fn of(pistons: &Pistons, pushing: Option<Facing>) -> MovingShapes {
let mut out = MovingShapes::default();
for m in pistons.iter() {
out.add_block(m, pushing);
}
out
}
fn add_block(&mut self, m: &MovingBlock, pushing: Option<Facing>) {
let excluded = m.progress < 1.0 && pushing == Some(m.moves());
if excluded {
if !m.extending
&& m.source
&& let Shape::Grid { shape, full_cube } = collision_shape(
with(m.pushed, "extended", "true"),
m.pos[0],
m.pos[1],
m.pos[2],
None,
)
{
self.shapes.push((m.pos, Placed::Static(shape, full_cube)));
}
return;
}
if m.source {
let k = if m.extending {
0
} else if m.pushed.block() == Block::STICKY_PISTON {
2
} else {
1
};
let pi = if m.progress == 0.0 {
Some(0)
} else if m.progress == 0.5 {
Some(1)
} else if m.progress == 1.0 {
Some(2)
} else {
None
};
if let Some(pi) = pi {
let t = &SOURCE_SHAPES[m.facing as usize][k][pi];
let axes = if t.simple {
[
Points::Fractional(t.sizes[0] as u32),
Points::Fractional(t.sizes[1] as u32),
Points::Fractional(t.sizes[2] as u32),
]
} else {
[
Points::Explicit(t.xs),
Points::Explicit(t.ys),
Points::Explicit(t.zs),
]
};
let full = t.simple && t.sizes == [1, 1, 1];
let shape = VoxelShape {
axes,
cells: t.cells,
};
self.shapes.push((m.pos, Placed::Static(shape, full)));
return;
}
}
let state = if m.source {
let mut h = with(
Block::PISTON_HEAD.default_state(),
"facing",
FACING_NAMES[m.facing as usize],
);
let short = m.extending != (1.0 - m.progress < 0.25);
h = with(h, "short", if short { "true" } else { "false" });
h
} else {
m.pushed
};
let f = m.shift(m.progress);
let o = offset(m.facing);
let (d, e, g) = (
f64::from(o[0] as f32 * f),
f64::from(o[1] as f32 * f),
f64::from(o[2] as f32 * f),
);
for b in state.collision().boxes {
let shifted = Aabb::new(
b.min_x + d,
b.min_y + e,
b.min_z + g,
b.max_x + d,
b.max_y + e,
b.max_z + g,
);
if let Some(s) = OwnedShape::cuboid(&shifted) {
self.shapes.push((m.pos, Placed::Owned(s)));
}
}
}
pub(crate) fn at(&self, pos: [i32; 3]) -> impl Iterator<Item = (VoxelShape<'_>, bool)> {
self.shapes
.iter()
.filter(move |(p, _)| *p == pos)
.map(|(_, s)| match s {
Placed::Owned(o) => (o.view(), o.full),
Placed::Static(v, full) => (*v, *full),
})
}
}
struct Layered<'a, W> {
w: &'a W,
edits: &'a [([i32; 3], BlockState)],
}
impl<W: BlockView<State = BlockState>> BlockView for Layered<'_, W> {
type State = BlockState;
#[inline]
fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
for (p, s) in self.edits.iter().rev() {
if *p == [x, y, z] {
return *s;
}
}
self.w.block(x, y, z)
}
#[inline]
fn is_chunk_loaded(&self, cx: i32, cz: i32) -> bool {
self.w.is_chunk_loaded(cx, cz)
}
#[inline]
fn world_border(&self) -> WorldBorder {
self.w.world_border()
}
}
struct Overlay<'a, W> {
w: &'a W,
edits: &'a mut Edits,
start: usize,
pistons: &'a mut Pistons,
}
#[inline]
fn valid(p: [i32; 3]) -> bool {
(0..256).contains(&p[1])
}
impl<W: BlockView<State = BlockState>> Overlay<'_, W> {
fn get(&self, p: [i32; 3]) -> BlockState {
if !valid(p) {
return BlockState::AIR;
}
let v = Layered {
w: self.w,
edits: &self.edits[self.start..],
};
v.block(p[0], p[1], p[2])
}
fn set(&mut self, p: [i32; 3], s: BlockState) {
if !valid(p) || !self.w.is_chunk_loaded(p[0] >> 4, p[2] >> 4) {
return;
}
let old = self.get(p);
if old == s {
return;
}
if old.block() == Block::MOVING_PISTON
&& s.block() != Block::MOVING_PISTON
&& let Some(i) = self.pistons.index_at(p)
{
self.pistons.blocks[i].removed = true;
}
self.edits.push((p, s));
}
fn add_moving(
&mut self,
pos: [i32; 3],
pushed: BlockState,
facing: Facing,
extending: bool,
source: bool,
) {
if !valid(pos) || !self.w.is_chunk_loaded(pos[0] >> 4, pos[2] >> 4) {
return;
}
self.pistons.add(MovingBlock {
pos,
pushed,
facing,
extending,
source,
progress: 0.0,
last_progress: 0.0,
hold: 0,
removed: false,
});
}
fn finish(&mut self, i: usize) {
let b = self.pistons.blocks[i];
let m = &mut self.pistons.blocks[i];
m.progress = 1.0;
m.last_progress = 1.0;
m.removed = true;
if self.get(b.pos).block() == Block::MOVING_PISTON {
self.set(b.pos, if b.source { BlockState::AIR } else { b.pushed });
}
}
fn moving_state(facing: Facing, sticky: bool) -> BlockState {
let s = with(
Block::MOVING_PISTON.default_state(),
"facing",
FACING_NAMES[facing as usize],
);
if sticky { with(s, "type", "sticky") } else { s }
}
fn on_event(&mut self, pos: [i32; 3], action: u8, data: u8) -> bool {
let state = self.get(pos);
if !is_piston(state.block()) {
return false;
}
let Some(facing) = facing_of(state) else {
return false;
};
let sticky = state.block() == Block::STICKY_PISTON;
match action {
0 => {
if !self.move_blocks(pos, facing, true, sticky) {
return true;
}
self.set(pos, with(state, "extended", "true"));
}
1 | 2 => {
if let Some(i) = self.pistons.index_at(step(pos, facing, 1)) {
self.finish(i);
}
self.set(pos, Self::moving_state(facing, sticky));
let base = with(
state.block().default_state(),
"facing",
FACING_NAMES[(data & 7) as usize % 6],
);
self.add_moving(pos, base, facing, false, true);
if sticky {
let p2 = step(pos, facing, 2);
let b = self.get(p2);
let mut finished = false;
if b.block() == Block::MOVING_PISTON
&& let Some(i) = self.pistons.index_at(p2)
&& self.pistons.blocks[i].facing == facing
&& self.pistons.blocks[i].extending
{
self.finish(i);
finished = true;
}
if !finished {
let id = b.block().id();
if action != 1
|| b.is_air()
|| !self.movable(b, p2, opposite(facing), false, facing)
|| (behaviour(id) != Behaviour::Normal && !is_piston(b.block()))
{
self.set(step(pos, facing, 1), BlockState::AIR);
} else {
self.move_blocks(pos, facing, false, sticky);
}
}
} else {
self.set(step(pos, facing, 1), BlockState::AIR);
}
}
_ => {}
}
true
}
fn movable(
&self,
b: BlockState,
p: [i32; 3],
dir: Facing,
can_break: bool,
piston: Facing,
) -> bool {
if !valid(p) || !self.w.world_border().contains_block(p[0], p[2]) {
return false;
}
if b.is_air() {
return true;
}
let blk = b.block();
if blk == Block::OBSIDIAN || blk == Block::CRYING_OBSIDIAN || blk == Block::RESPAWN_ANCHOR {
return false;
}
if (dir == 0 && p[1] == 0) || (dir == 1 && p[1] == 255) {
return false;
}
if is_piston(blk) {
if b.get(prop("extended")) == Some("true") {
return false;
}
} else {
let id = blk.id();
if unbreakable(id) {
return false;
}
match behaviour(id) {
Behaviour::Block => return false,
Behaviour::Destroy => return can_break,
Behaviour::PushOnly => return dir == piston,
Behaviour::Normal => {}
}
}
!has_block_entity(blk.id())
}
fn move_blocks(&mut self, pos: [i32; 3], facing: Facing, extend: bool, sticky: bool) -> bool {
let head_pos = step(pos, facing, 1);
if !extend && self.get(head_pos).block() == Block::PISTON_HEAD {
self.set(head_pos, BlockState::AIR);
}
let mut h = Handler::new(pos, facing, extend);
if !h.calculate(self) {
return false;
}
let states: Vec<BlockState> = h.moved.iter().map(|&m| self.get(m)).collect();
let mut vacated: Vec<[i32; 3]> = h.moved.clone();
let push = if extend { facing } else { opposite(facing) };
for &b in h.broken.iter().rev() {
self.set(b, BlockState::AIR);
}
for (k, &m) in h.moved.iter().enumerate().rev() {
let dst = step(m, push, 1);
vacated.retain(|v| *v != dst);
self.set(dst, Self::moving_state(facing, false));
self.add_moving(dst, states[k], facing, extend, false);
}
if extend {
vacated.retain(|v| *v != head_pos);
self.set(head_pos, Self::moving_state(facing, sticky));
let mut head = with(
Block::PISTON_HEAD.default_state(),
"facing",
FACING_NAMES[facing as usize],
);
if sticky {
head = with(head, "type", "sticky");
}
self.add_moving(head_pos, head, facing, true, true);
}
for v in vacated {
self.set(v, BlockState::AIR);
}
true
}
}
struct Handler {
from: [i32; 3],
to: [i32; 3],
motion: Facing,
piston: Facing,
extend: bool,
moved: Vec<[i32; 3]>,
broken: Vec<[i32; 3]>,
}
impl Handler {
fn new(pos: [i32; 3], facing: Facing, extend: bool) -> Handler {
let (motion, to) = if extend {
(facing, step(pos, facing, 1))
} else {
(opposite(facing), step(pos, facing, 2))
};
Handler {
from: pos,
to,
motion,
piston: facing,
extend,
moved: Vec::new(),
broken: Vec::new(),
}
}
fn calculate<W: BlockView<State = BlockState>>(&mut self, ov: &Overlay<'_, W>) -> bool {
self.moved.clear();
self.broken.clear();
let b = ov.get(self.to);
if !ov.movable(b, self.to, self.motion, false, self.piston) {
if self.extend && behaviour(b.block().id()) == Behaviour::Destroy {
self.broken.push(self.to);
return true;
}
return false;
}
if !self.try_move(ov, self.to, self.motion) {
return false;
}
let mut i = 0;
while i < self.moved.len() {
let p = self.moved[i];
if is_sticky_block(ov.get(p).block()) && !self.move_adjacent(ov, p) {
return false;
}
i += 1;
}
true
}
fn try_move<W: BlockView<State = BlockState>>(
&mut self,
ov: &Overlay<'_, W>,
pos: [i32; 3],
dir: Facing,
) -> bool {
let mut b = ov.get(pos);
if b.is_air()
|| !ov.movable(b, pos, self.motion, false, dir)
|| pos == self.from
|| self.moved.contains(&pos)
{
return true;
}
let back = opposite(self.motion);
let mut i = 1usize;
if i + self.moved.len() > PUSH_LIMIT {
return false;
}
while is_sticky_block(b.block()) {
let bp = step(pos, back, i as i32);
let prev = b.block();
b = ov.get(bp);
if b.is_air()
|| !stuck(prev, b.block())
|| !ov.movable(b, bp, self.motion, false, back)
|| bp == self.from
{
break;
}
i += 1;
if i + self.moved.len() > PUSH_LIMIT {
return false;
}
}
let mut j = 0usize;
for k in (0..i).rev() {
self.moved.push(step(pos, back, k as i32));
j += 1;
}
let mut l = 1;
loop {
let bp = step(pos, self.motion, l);
if let Some(m) = self.moved.iter().position(|&p| p == bp) {
self.reorder(j, m);
for n in 0..=m + j {
let p = self.moved[n];
if is_sticky_block(ov.get(p).block()) && !self.move_adjacent(ov, p) {
return false;
}
}
return true;
}
let b = ov.get(bp);
if b.is_air() {
return true;
}
if !ov.movable(b, bp, self.motion, true, self.motion) || bp == self.from {
return false;
}
if behaviour(b.block().id()) == Behaviour::Destroy {
self.broken.push(bp);
return true;
}
if self.moved.len() >= PUSH_LIMIT {
return false;
}
self.moved.push(bp);
j += 1;
l += 1;
}
}
fn reorder(&mut self, from: usize, to: usize) {
let n = self.moved.len();
let mut v = Vec::with_capacity(n);
v.extend_from_slice(&self.moved[..to]);
v.extend_from_slice(&self.moved[n - from..]);
v.extend_from_slice(&self.moved[to..n - from]);
self.moved = v;
}
fn move_adjacent<W: BlockView<State = BlockState>>(
&mut self,
ov: &Overlay<'_, W>,
pos: [i32; 3],
) -> bool {
let s = ov.get(pos).block();
for d in 0..6 {
if axis(d) != axis(self.motion) {
let q = step(pos, d, 1);
if stuck(ov.get(q).block(), s) && !self.try_move(ov, q, d) {
return false;
}
}
}
true
}
}
pub(super) struct Distinct<'a, W>(pub(super) &'a W);
impl<W: BlockView<State = BlockState>> BlockView for Distinct<'_, W> {
type State = BlockState;
#[inline(always)]
fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
self.0.block(x, y, z)
}
#[inline(always)]
fn is_chunk_loaded(&self, cx: i32, cz: i32) -> bool {
self.0.is_chunk_loaded(cx, cz)
}
#[inline(always)]
fn world_border(&self) -> WorldBorder {
self.0.world_border()
}
}
#[allow(clippy::too_many_arguments)]
pub fn tick_with_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
input: &TickInput,
world: &W,
pistons: &mut Pistons,
time: i64,
out: &mut Packets,
edits: &mut Edits,
) {
tick_player_among_pistons(p, x, around, input, world, pistons, out);
pistons.tick_after_entities(p, x, around, world, time, edits);
}
pub fn tick_player_among_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
input: &TickInput,
world: &W,
pistons: &Pistons,
out: &mut Packets,
) {
let view = Distinct(world);
let shapes = MovingShapes::of(pistons, None);
tick_with_moving(p, x, around, input, &view, &shapes, out);
}
impl Pistons {
pub fn tick_after_entities<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
world: &W,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
tick_moving(Some((p, x, around)), world, time, self, edits);
}
}
}
type PlayerRef<'a, 'b> = (&'a mut PlayerState, &'a mut PlayerExt, &'a Surroundings<'b>);
fn tick_moving<W: BlockView<State = BlockState>>(
mut p: Option<PlayerRef<'_, '_>>,
world: &W,
time: i64,
pistons: &mut Pistons,
edits: &mut Edits,
) {
let border = world.world_border();
let start = edits.len();
let mut i = 0;
while i < pistons.blocks.len() {
let b = pistons.blocks[i];
i += 1;
if b.removed || !valid(b.pos) || !border.contains_block(b.pos[0], b.pos[2]) {
continue;
}
let m = &mut pistons.blocks[i - 1];
m.last_progress = m.progress;
if m.last_progress >= 1.0 {
if m.hold < CLIENT_HOLD {
m.hold += 1;
continue;
}
m.removed = true;
let m = *m;
let mut ov = Overlay {
w: world,
edits,
start,
pistons,
};
if ov.get(m.pos).block() == Block::MOVING_PISTON {
ov.set(m.pos, m.pushed);
}
} else {
let f = m.progress + 0.5;
let m = *m;
if let Some((p, x, around)) = p.as_mut() {
let view = Layered {
w: world,
edits: &edits[start..],
};
let view = Distinct(&view);
let mut cx = PushCx {
p,
x,
around,
world: &view,
time,
pistons,
};
cx.push(&m, f);
cx.honey(&m, f);
}
let m = &mut pistons.blocks[i - 1];
m.progress = f;
if m.progress >= 1.0 {
m.progress = 1.0;
}
}
}
pistons.drop_removed();
}
fn stretch(b: &Aabb, dir: Facing, d: f64) -> Aabb {
let e = if dir & 1 == 1 { d } else { -d };
let (f, g) = (e.min(0.0), e.max(0.0));
match dir {
4 => sorted_box(b.min_x + f, b.min_y, b.min_z, b.min_x + g, b.max_y, b.max_z),
5 => sorted_box(b.max_x + f, b.min_y, b.min_z, b.max_x + g, b.max_y, b.max_z),
0 => sorted_box(b.min_x, b.min_y + f, b.min_z, b.max_x, b.min_y + g, b.max_z),
2 => sorted_box(b.min_x, b.min_y, b.min_z + f, b.max_x, b.max_y, b.min_z + g),
3 => sorted_box(b.min_x, b.min_y, b.max_z + f, b.max_x, b.max_y, b.max_z + g),
_ => sorted_box(b.min_x, b.max_y + f, b.min_z, b.max_x, b.max_y + g, b.max_z),
}
}
fn reach(b: &Aabb, dir: Facing, e: &Aabb) -> f64 {
match dir {
5 => b.max_x - e.min_x,
4 => e.max_x - b.min_x,
0 => e.max_y - b.min_y,
3 => b.max_z - e.min_z,
2 => e.max_z - b.min_z,
_ => b.max_y - e.min_y,
}
}
fn union(a: &Aabb, b: &Aabb) -> Aabb {
Aabb::new(
a.min_x.min(b.min_x),
a.min_y.min(b.min_y),
a.min_z.min(b.min_z),
a.max_x.max(b.max_x),
a.max_y.max(b.max_y),
a.max_z.max(b.max_z),
)
}
struct PushCx<'a, 'b, W> {
p: &'a mut PlayerState,
x: &'a mut PlayerExt,
around: &'a Surroundings<'b>,
world: &'a W,
time: i64,
pistons: &'a mut Pistons,
}
impl<W: BlockView<State = BlockState>> PushCx<'_, '_, W> {
fn place(m: &MovingBlock, b: &Aabb) -> Aabb {
let d = f64::from(m.shift(m.progress));
let o = offset(m.facing);
b.offset(
f64::from(m.pos[0]) + d * f64::from(o[0]),
f64::from(m.pos[1]) + d * f64::from(o[1]),
f64::from(m.pos[2]) + d * f64::from(o[2]),
)
}
fn push(&mut self, m: &MovingBlock, f: f32) {
let dir = m.moves();
let d = f64::from(f - m.progress);
let boxes = m.head_state().collision().boxes;
if boxes.is_empty() {
return;
}
let mut hull = boxes[0];
for b in &boxes[1..] {
hull = union(&hull, b);
}
let bx = Self::place(m, &hull);
let query = union(&stretch(&bx, dir, d), &bx);
if self.p.spectator || !self.p.bb.intersects(&query) {
return;
}
if m.pushed.block() == Block::SLIME_BLOCK {
let k = axis_index(dir);
self.p.vel[k] = f64::from(offset(dir)[k]);
}
let mut h: f64 = 0.0;
for b in boxes {
let b3 = stretch(&Self::place(m, b), dir, d);
if b3.intersects(&self.p.bb) {
h = h.max(reach(&b3, dir, &self.p.bb));
if h >= d {
break;
}
}
}
#[allow(clippy::neg_cmp_op_on_partial_ord)]
if !(h <= 0.0) {
let h = h.min(d) + 0.01;
self.move_by_piston(dir, dir, h);
if !m.extending && m.source {
self.pull_back(m, dir, d);
}
}
}
fn pull_back(&mut self, m: &MovingBlock, dir: Facing, amount: f64) {
let bb = self.p.bb;
let cell = Aabb::FULL.offset(
f64::from(m.pos[0]),
f64::from(m.pos[1]),
f64::from(m.pos[2]),
);
if !bb.intersects(&cell) {
return;
}
let back = opposite(dir);
let d = reach(&cell, back, &bb) + 0.01;
let inter = sorted_box(
bb.min_x.max(cell.min_x),
bb.min_y.max(cell.min_y),
bb.min_z.max(cell.min_z),
bb.max_x.min(cell.max_x),
bb.max_y.min(cell.max_y),
bb.max_z.min(cell.max_z),
);
let e = reach(&cell, back, &inter) + 0.01;
if (d - e).abs() < 0.01 {
let d = d.min(amount) + 0.01;
self.move_by_piston(dir, back, d);
}
}
fn honey(&mut self, m: &MovingBlock, f: f32) {
if m.pushed.block() != Block::HONEY_BLOCK {
return;
}
let dir = m.moves();
if axis(dir) == 0 {
return;
}
let top = m
.pushed
.collision()
.boxes
.iter()
.map(|b| b.max_y)
.fold(f64::NEG_INFINITY, f64::max);
let bx = Self::place(
m,
&Aabb::new(0.0, top, 0.0, 1.0, 1.500_000_099_999_999_8, 1.0),
);
let e = f64::from(f - m.progress);
let p = &*self.p;
if p.spectator
|| !p.on_ground
|| !p.bb.intersects(&bx)
|| !(p.pos[0] >= bx.min_x && p.pos[0] <= bx.max_x)
|| !(p.pos[2] >= bx.min_z && p.pos[2] <= bx.max_z)
{
return;
}
self.move_by_piston(dir, dir, e);
}
fn move_by_piston(&mut self, pushing: Facing, dir: Facing, e: f64) {
let o = offset(dir);
let mut d = [
e * f64::from(o[0]),
e * f64::from(o[1]),
e * f64::from(o[2]),
];
if self.p.no_clip {
return;
}
if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= 1.0e-7 {
} else {
if self.time != self.pistons.delta_time {
self.pistons.delta = [0.0; 3];
self.pistons.delta_time = self.time;
}
let Some(k) = [0, 1, 2].into_iter().find(|&k| d[k] != 0.0) else {
return;
};
let v = (d[k] + self.pistons.delta[k]).clamp(-0.51, 0.51);
let mv = v - self.pistons.delta[k];
self.pistons.delta[k] = v;
if mv.abs() <= f64::from(1.0e-5f32) {
return;
}
d = [0.0; 3];
d[k] = mv;
}
let shapes = MovingShapes::of(self.pistons, Some(pushing));
let cx = PlayerStepCtx {
x: self.x,
around: self.around,
shapes: &shapes,
};
piston_move(self.p, cx, self.world, d);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
#[test]
fn source_shapes_match_oracle_dump() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.16.5/piston_shapes.jsonl.gz");
let mut text = String::new();
flate2::read::GzDecoder::new(std::fs::File::open(path).expect("shapes"))
.read_to_string(&mut text)
.expect("gzip");
let bits = |v: &serde_json::Value| {
f64::from_bits(u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap())
};
let mut n = 0;
for line in text.lines() {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
let f = v["facing"].as_u64().unwrap() as usize;
let k = match v["kind"].as_str().unwrap() {
"head" => 0,
"base" => 1,
_ => 2,
};
let p = match v["progress"][1].as_str().unwrap() {
"00000000" => 0,
"3f000000" => 1,
_ => 2,
};
let t = &SOURCE_SHAPES[f][k][p];
assert_eq!(t.simple, v["class"] == "simple");
for (axis, pts) in [("x", t.xs), ("y", t.ys), ("z", t.zs)] {
let want: Vec<u64> = v[format!("points_{axis}")]
.as_array()
.unwrap()
.iter()
.map(|x| bits(x).to_bits())
.collect();
let got: Vec<u64> = pts.iter().map(|x| x.to_bits()).collect();
assert_eq!(got, want, "{line}");
}
for (i, c) in v["filled"].as_str().unwrap().chars().enumerate() {
assert_eq!(t.cells[i / 64] >> (i % 64) & 1 == 1, c == '1', "{line}");
}
n += 1;
}
assert_eq!(n, 54);
}
#[test]
fn facts_match_oracle_dump() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.16.5/piston_facts.jsonl.gz");
let mut text = String::new();
flate2::read::GzDecoder::new(std::fs::File::open(path).expect("facts"))
.read_to_string(&mut text)
.expect("gzip");
let mut n = 0;
for line in text.lines() {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
let id = v["block"].as_u64().unwrap() as u16;
let b = match v["piston"].as_u64().unwrap() {
0 => Behaviour::Normal,
1 => Behaviour::Destroy,
2 => Behaviour::Block,
_ => Behaviour::PushOnly,
};
assert_eq!(behaviour(id), b, "behaviour of {id}");
assert_eq!(
unbreakable(id),
v["unbreakable"].as_bool().unwrap(),
"hardness of {id}"
);
assert_eq!(
has_block_entity(id),
v["block_entity"].as_bool().unwrap(),
"block entity of {id}"
);
assert!(v["same_for_all_states"].as_bool().unwrap());
let blk = Block::from_id(id).expect("block");
assert_eq!(blk.name(), v["name"].as_str().unwrap());
n += 1;
}
assert!(n > 700);
}
}