use ghast_data::v1_8::{Block, BlockState};
use super::blocks::{is_valid_pos, state_at};
use super::player::{Options, PlayerState, other_push_move, push_move, tick_with_moving};
use crate::input::{Packets, TickInput};
use crate::math::{Aabb, BoxOps, sorted_box};
use crate::world::{BlockView, WorldBorder};
pub const MOVING_PISTON: u8 = 36;
const STICKY_PISTON: u8 = 29;
const PISTON: u8 = 33;
const PISTON_HEAD: u8 = 34;
const OBSIDIAN: u8 = 49;
const SLIME: u8 = 165;
const PUSH_LIMIT: usize = 12;
pub type Facing = u8;
#[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]
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]
}
#[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,
removed: bool,
stale: bool,
}
impl MovingBlock {
#[must_use]
pub fn collision_box(&self) -> Option<Aabb> {
self.collision_box_with(FULL)
}
#[must_use]
pub fn collision_box_with(&self, head: [f64; 6]) -> Option<Aabb> {
let f = if self.extending {
1.0 - self.last_progress
} else {
self.last_progress
};
shrunk_box(self.pushed, self.pos, f, self.facing, head)
}
}
fn base_box(s: BlockState, head: [f64; 6]) -> Option<[f64; 6]> {
match s.block().id() {
PISTON | STICKY_PISTON => Some(FULL),
PISTON_HEAD => Some(head),
_ => s
.collision()
.boxes
.first()
.map(|b| [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]),
}
}
#[must_use]
pub fn box_is_tracked(s: BlockState) -> bool {
match s.block().id() {
PISTON | STICKY_PISTON | PISTON_HEAD => true,
78 | 88 | 60 | 171 => true,
_ => {
let c = s.collision();
c.boxes.is_empty() || c.is_full_cube()
}
}
}
fn shrunk_box(
s: BlockState,
pos: [i32; 3],
progress: f32,
facing: Facing,
head: [f64; 6],
) -> Option<Aabb> {
if s.block().id() == MOVING_PISTON || s.is_air() {
return None;
}
let b = base_box(s, head)?;
let (x, y, z) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]));
let mut v = [x + b[0], y + b[1], z + b[2], x + b[3], y + b[4], z + b[5]];
let o = offset(facing);
for axis in 0..3 {
let d = f64::from(o[axis] as f32 * progress);
if o[axis] < 0 {
v[axis] -= d;
} else {
v[axis + 3] -= d;
}
}
Some(sorted_box(v[0], v[1], v[2], v[3], v[4], v[5]))
}
pub type Edits = Vec<([i32; 3], BlockState)>;
#[derive(Clone, Debug, PartialEq)]
pub struct Pistons {
blocks: Vec<MovingBlock>,
head: std::cell::Cell<u8>,
unmodelled: bool,
head_unknown: std::cell::Cell<u8>,
ray_needed: std::cell::Cell<bool>,
heads_loaded: std::cell::Cell<bool>,
}
impl Default for Pistons {
fn default() -> Pistons {
Pistons::new()
}
}
const FULL: [f64; 6] = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
const HEAD_FULL: u8 = 6;
const HEAD_FULL_RAY: u8 = 7;
const HEAD_FULL_WATCH: u8 = 8;
const HEAD_PLATE: [[f64; 6]; 6] = [
[0.0, 0.0, 0.0, 1.0, 0.25, 1.0],
[0.0, 0.75, 0.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 1.0, 1.0, 0.25],
[0.0, 0.0, 0.75, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 0.25, 1.0, 1.0],
[0.75, 0.0, 0.0, 1.0, 1.0, 1.0],
];
impl Pistons {
#[must_use]
pub const fn new() -> Pistons {
Pistons {
blocks: Vec::new(),
head: std::cell::Cell::new(HEAD_FULL),
unmodelled: false,
head_unknown: std::cell::Cell::new(0),
ray_needed: std::cell::Cell::new(false),
heads_loaded: std::cell::Cell::new(false),
}
}
#[must_use]
pub fn head_bounds(&self) -> [f64; 6] {
match self.head.get() {
f @ 0..=5 => HEAD_PLATE[f as usize],
_ => FULL,
}
}
#[inline]
#[must_use]
pub fn head_bounds_set(&self) -> bool {
self.head.get() != HEAD_FULL
}
pub fn set_ray_needed(&self, on: bool) {
self.ray_needed.set(on);
if self.head.get() >= HEAD_FULL {
self.head.set(self.full_code());
}
}
pub fn set_heads_loaded(&self, on: bool) {
self.heads_loaded.set(on);
if self.head.get() >= HEAD_FULL {
self.head.set(self.full_code());
}
}
#[inline]
#[must_use]
pub fn watch_only(&self) -> bool {
self.head.get() == HEAD_FULL_WATCH
}
fn full_code(&self) -> u8 {
if self.ray_needed.get() {
HEAD_FULL_RAY
} else if self.heads_loaded.get() {
HEAD_FULL_WATCH
} else {
HEAD_FULL
}
}
pub fn crosshair<W: BlockView<State = BlockState>>(
&self,
world: &W,
eye: [f64; 3],
look: [f64; 3],
reach: f64,
) {
let end = crate::pick::legacy::ray_end(eye, look, reach);
let mut last = None;
crate::pick::legacy::trace(eye, end, true, |p| {
let s = state_at(world, p[0], p[1], p[2]);
if s.block().id() == PISTON_HEAD && s.meta() & 7 <= 5 {
last = Some(s.meta() & 7);
}
crate::pick::v1_8::shape(world, p, false)
});
if let Some(f) = last {
self.head.set(f);
self.head_unknown.set(0);
}
}
pub fn forget_head_bounds(&self, facings: u8) {
let full = u8::from(self.head.get() < HEAD_FULL) << 6;
self.head_unknown
.set(self.head_unknown.get() | (facings & 0x3f) | full);
}
#[must_use]
pub fn untracked_near(&self, bb: &Aabb) -> bool {
let area = bb.grow(1.0, 1.0, 1.0);
self.iter().any(|m| {
!box_is_tracked(m.pushed)
&& 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,
))
})
}
pub fn take_unmodelled(&mut self) -> bool {
std::mem::take(&mut self.unmodelled)
}
#[must_use]
pub fn head_unknown_touching(&self, before: &Aabb, after: &Aabb) -> bool {
if self.head_unknown.get() == 0 {
return false;
}
let swept = Aabb::new(
before.min_x.min(after.min_x) - 0.01,
before.min_y.min(after.min_y) - 0.01,
before.min_z.min(after.min_z) - 0.01,
before.max_x.max(after.max_x) + 0.01,
before.max_y.max(after.max_y) + 0.61,
before.max_z.max(after.max_z) + 0.01,
);
self.iter().any(|m| {
m.pushed.block().id() == PISTON_HEAD
&& m.collision_box_with(FULL)
.is_some_and(|b| b.intersects(&swept))
})
}
#[inline]
pub(super) fn head_queried(&self) {
self.head.set(self.full_code());
self.head_unknown.set(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 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 block_changed(&mut self, pos: [i32; 3], old: BlockState, new: BlockState) {
if old.block().id() == MOVING_PISTON
&& new.block().id() != 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;
self.blocks[i].stale = true;
}
b.removed = false;
self.blocks.push(b);
}
pub fn tick_blocks<W: BlockView<State = BlockState>>(&mut self, world: &W, edits: &mut Edits) {
if !self.is_empty() {
tick_moving(None, world, &Options::default(), self, &mut [], &[], edits);
}
}
pub fn tick_blocks_among<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
options: &Options,
others: &mut [PistonEntity],
solids: &[(Aabb, [i32; 3])],
edits: &mut Edits,
) {
if !self.is_empty() {
tick_moving(None, world, options, self, others, solids, edits);
}
}
pub fn tick_after_entities<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
world: &W,
options: &Options,
edits: &mut Edits,
) {
if !self.is_empty() {
tick_moving(Some(p), world, options, self, &mut [], &[], edits);
}
}
pub fn tick_after_entities_among<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
world: &W,
options: &Options,
others: &mut [PistonEntity],
solids: &[(Aabb, [i32; 3])],
edits: &mut Edits,
) {
if !self.is_empty() {
tick_moving(Some(p), world, options, self, others, solids, edits);
}
}
pub fn retain(&mut self, mut keep: impl FnMut(&MovingBlock) -> bool) {
self.blocks.retain(|b| b.stale || (!b.removed && keep(b)));
}
fn drop_removed(&mut self) {
self.blocks.retain(|b| b.stale || !b.removed);
}
pub fn block_event<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
pos: [i32; 3],
block: u8,
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, block, action, data);
self.drop_removed();
r
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PistonEntity {
pub bb: Aabb,
pub pos: [f64; 3],
pub on_ground: bool,
pub in_web: bool,
pub step_height: f32,
pub sneaking: bool,
pub moved: bool,
pub followed: bool,
pub section: [i32; 3],
}
#[must_use]
pub fn search_finds(section: [i32; 3], q: &Aabb) -> bool {
let f = |v: f64| crate::math::floor(v / 16.0);
let (x0, x1) = (f(q.min_x - 2.0), f(q.max_x + 2.0));
let (z0, z1) = (f(q.min_z - 2.0), f(q.max_z + 2.0));
let (y0, y1) = (f(q.min_y - 2.0).clamp(0, 15), f(q.max_y + 2.0).clamp(0, 15));
(x0..=x1).contains(§ion[0])
&& (y0..=y1).contains(§ion[1])
&& (z0..=z1).contains(§ion[2])
}
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,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Behaviour {
Normal,
Destroy,
Block,
}
fn behaviour(id: u8) -> Behaviour {
match id {
6
| 8..=11
| 18
| 26
| 30..=32
| 37..=40
| 50
| 51
| 55
| 59
| 64
| 65
| 69..=72
| 75..=78
| 81
| 83
| 86
| 91..=94
| 103..=106
| 111
| 115
| 122
| 127
| 131
| 132
| 140..=144
| 147..=150
| 161
| 175
| 193..=197 => Behaviour::Destroy,
29 | 33 | 34 | 36 | 90 | 119 | 145 | 166 => Behaviour::Block,
_ => Behaviour::Normal,
}
}
fn unbreakable(id: u8) -> bool {
matches!(id, 7 | 36 | 90 | 119 | 120 | 137 | 166)
}
fn has_block_entity(id: u8) -> bool {
matches!(
id,
23 | 25
| 36
| 52
| 54
| 61..=63
| 68
| 84
| 116
| 117
| 119
| 130
| 137
| 138
| 140
| 144
| 146
| 149
| 150
| 151
| 154
| 158
| 176..=178
)
}
#[inline]
fn is_piston(id: u8) -> bool {
id == PISTON || id == STICKY_PISTON
}
fn facing_of(s: BlockState) -> Option<Facing> {
match s.block().id() {
PISTON | STICKY_PISTON | PISTON_HEAD | MOVING_PISTON => {
let f = s.meta() & 7;
(f <= 5).then_some(f)
}
_ => None,
}
}
impl<W: BlockView<State = BlockState>> Overlay<'_, W> {
#[inline]
fn get(&self, p: [i32; 3]) -> BlockState {
let v = Layered {
w: self.w,
edits: &self.edits[self.start..],
};
state_at(&v, p[0], p[1], p[2])
}
fn set(&mut self, p: [i32; 3], s: BlockState) {
if !is_valid_pos(p[0], p[1], p[2]) || !self.w.is_chunk_loaded(p[0] >> 4, p[2] >> 4) {
return;
}
let old = self.get(p);
if old == s {
return;
}
if old.block().id() == MOVING_PISTON
&& s.block().id() != 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 !is_valid_pos(pos[0], pos[1], pos[2])
|| !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,
removed: false,
stale: false,
});
}
fn finish(&mut self, i: usize) {
let b = self.pistons.blocks[i];
if b.last_progress < 1.0 {
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().id() == MOVING_PISTON {
self.set(b.pos, b.pushed);
}
}
}
fn on_event(&mut self, pos: [i32; 3], block: u8, action: u8, data: u8) -> bool {
let state = self.get(pos);
let Some(facing) = facing_of(state) else {
return false;
};
let sticky = block == STICKY_PISTON;
match action {
0 => {
if !self.move_blocks(pos, facing, true, sticky) {
return true;
}
if is_piston(state.block().id()) {
self.set(pos, BlockState::new(state.block(), state.meta() | 8));
}
}
1 => {
if let Some(i) = self.pistons.index_at(step(pos, facing, 1)) {
self.finish(i);
}
let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
self.set(
pos,
BlockState::new(moving, facing | if sticky { 8 } else { 0 }),
);
let base = Block::from_id(block).unwrap_or(state.block());
self.add_moving(pos, BlockState::new(base, data & 15), facing, false, true);
if sticky {
let p2 = step(pos, facing, 2);
let b = self.get(p2);
let mut finished = false;
if b.block().id() == 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;
}
let id = b.block().id();
if !finished
&& !b.is_air()
&& self.movable(b, p2, opposite(facing), false)
&& (behaviour(id) == Behaviour::Normal || is_piston(id))
{
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) -> bool {
let id = b.block().id();
if id == OBSIDIAN {
return false;
}
if !self.w.world_border().contains_block(p[0], p[2]) {
return false;
}
if p[1] < 0 || (dir == 0 && p[1] == 0) || p[1] > 255 || (dir == 1 && p[1] == 255) {
return false;
}
if is_piston(id) {
if self.get(p).meta() & 8 != 0 {
return false;
}
} else {
if unbreakable(id) {
return false;
}
match behaviour(id) {
Behaviour::Block => return false,
Behaviour::Destroy => return can_break,
Behaviour::Normal => {}
}
}
!has_block_entity(id)
}
fn move_blocks(&mut self, pos: [i32; 3], facing: Facing, extend: bool, sticky: bool) -> bool {
if !extend {
self.set(step(pos, facing, 1), BlockState::AIR);
}
let mut h = Handler::new(pos, facing, extend);
if !h.calculate(self) {
return false;
}
let push = if extend { facing } else { opposite(facing) };
for &b in h.broken.iter().rev() {
self.set(b, BlockState::AIR);
}
let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
for &m in h.moved.iter().rev() {
let s = self.get(m);
self.set(m, BlockState::AIR);
let dst = step(m, push, 1);
self.set(dst, BlockState::new(moving, facing));
self.add_moving(dst, s, facing, extend, false);
}
if extend {
let head_pos = step(pos, facing, 1);
let t = if sticky { 8 } else { 0 };
let head = Block::from_id(PISTON_HEAD).expect("piston head");
self.set(head_pos, BlockState::new(moving, facing | t));
self.add_moving(
head_pos,
BlockState::new(head, facing | t),
facing,
true,
false,
);
}
true
}
}
struct Handler {
from: [i32; 3],
to: [i32; 3],
dir: Facing,
moved: Vec<[i32; 3]>,
broken: Vec<[i32; 3]>,
}
impl Handler {
fn new(pos: [i32; 3], facing: Facing, extend: bool) -> Handler {
let (dir, to) = if extend {
(facing, step(pos, facing, 1))
} else {
(opposite(facing), step(pos, facing, 2))
};
Handler {
from: pos,
to,
dir,
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.dir, false) {
if behaviour(b.block().id()) != Behaviour::Destroy {
return false;
}
self.broken.push(self.to);
return true;
}
if !self.try_move(ov, self.to) {
return false;
}
let mut i = 0;
while i < self.moved.len() {
let p = self.moved[i];
if ov.get(p).block().id() == SLIME && !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],
) -> bool {
let mut b = ov.get(pos);
if b.is_air()
|| !ov.movable(b, pos, self.dir, false)
|| pos == self.from
|| self.moved.contains(&pos)
{
return true;
}
let back = opposite(self.dir);
let mut i = 1usize;
if i + self.moved.len() > PUSH_LIMIT {
return false;
}
while b.block().id() == SLIME {
let bp = step(pos, back, i as i32);
b = ov.get(bp);
if b.is_air() || !ov.movable(b, bp, self.dir, false) || 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.dir, 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 ov.get(p).block().id() == SLIME && !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.dir, true) || 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 {
for d in 0..6 {
if axis(d) != axis(self.dir) && !self.try_move(ov, step(pos, d, 1)) {
return false;
}
}
true
}
}
pub fn tick_with_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
input: &TickInput,
world: &W,
options: &Options,
pistons: &mut Pistons,
out: &mut Packets,
edits: &mut Edits,
) {
let view = Distinct(world);
tick_with_moving(p, input, &view, options, pistons, out);
tick_moving(Some(p), world, options, pistons, &mut [], &[], edits);
}
pub fn tick_player_among_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
input: &TickInput,
world: &W,
options: &Options,
pistons: &Pistons,
out: &mut Packets,
) {
let view = Distinct(world);
tick_with_moving(p, input, &view, options, pistons, out);
}
struct Distinct<'a, W>(&'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()
}
}
fn tick_moving<W: BlockView<State = BlockState>>(
mut p: Option<&mut PlayerState>,
world: &W,
options: &Options,
pistons: &mut Pistons,
others: &mut [PistonEntity],
solids: &[(Aabb, [i32; 3])],
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.stale {
pistons.blocks[i - 1].stale = false;
if let Some(j) = pistons.index_at(b.pos) {
pistons.blocks[j].removed = true;
}
continue;
}
if b.removed || !(0..256).contains(&b.pos[1]) || !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 {
let m = *m;
if p.is_some() || !others.is_empty() {
let mut a = Pushes {
p: p.as_deref_mut(),
others,
solids,
};
push(
&mut a,
world,
options,
pistons,
&edits[start..],
&m,
1.0,
0.25,
);
}
pistons.blocks[i - 1].removed = true;
let mut ov = Overlay {
w: world,
edits,
start,
pistons,
};
if ov.get(m.pos).block().id() == MOVING_PISTON {
ov.set(m.pos, m.pushed);
}
} else {
m.progress += 0.5;
if m.progress >= 1.0 {
m.progress = 1.0;
}
let m = *m;
if m.extending && (p.is_some() || !others.is_empty()) {
let distance = m.progress - m.last_progress + 0.0625;
let mut a = Pushes {
p: p.as_deref_mut(),
others,
solids,
};
push(
&mut a,
world,
options,
pistons,
&edits[start..],
&m,
m.progress,
distance,
);
}
}
}
pistons.drop_removed();
}
struct Pushes<'a, 'b, 'c> {
p: Option<&'a mut PlayerState>,
others: &'b mut [PistonEntity],
solids: &'c [(Aabb, [i32; 3])],
}
#[allow(clippy::too_many_arguments)]
fn push<W: BlockView<State = BlockState>>(
a: &mut Pushes<'_, '_, '_>,
world: &W,
options: &Options,
pistons: &mut Pistons,
edits: &[([i32; 3], BlockState)],
m: &MovingBlock,
progress: f32,
distance: f32,
) {
let progress = if m.extending {
1.0 - progress
} else {
progress - 1.0
};
let Some(bx) = shrunk_box(m.pushed, m.pos, progress, m.facing, pistons.head_bounds()) else {
return;
};
let o = offset(m.facing);
let slime = m.pushed.block().id() == SLIME && m.extending;
let d = [
f64::from(distance * o[0] as f32),
f64::from(distance * o[1] as f32),
f64::from(distance * o[2] as f32),
];
let view = Layered { w: world, edits };
if m.pushed.block().id() == PISTON_HEAD && pistons.head_unknown.get() != 0 {
plate_check(a, pistons, m, progress, &bx);
}
if let Some(p) = a.p.as_deref_mut()
&& !p.spectator
&& p.bb.intersects(&bx)
{
if slime {
let axis = axis(m.facing) as usize;
let i = [1, 2, 0][axis];
p.vel[i] = f64::from(o[i]);
} else {
push_move(p, &view, options, pistons, d);
}
}
if a.others.is_empty() {
return;
}
push_others(a, &view, options, pistons, &bx, slime, d);
}
#[cold]
#[inline(never)]
fn plate_check(
a: &Pushes<'_, '_, '_>,
pistons: &mut Pistons,
m: &MovingBlock,
progress: f32,
bx: &Aabb,
) {
let mask = pistons.head_unknown.get();
for (f, plate) in HEAD_PLATE.into_iter().chain([FULL]).enumerate() {
if mask & (1 << f) == 0 {
continue;
}
let alt = shrunk_box(m.pushed, m.pos, progress, m.facing, plate);
let differs = |bb: &Aabb| bb.intersects(bx) != alt.is_some_and(|b| bb.intersects(&b));
let player =
a.p.as_deref()
.is_some_and(|p| !p.spectator && differs(&p.bb));
let other = a
.others
.iter()
.any(|e| e.moved && search_finds(e.section, bx) && differs(&e.bb));
if player || other {
pistons.unmodelled = true;
return;
}
}
}
#[cold]
#[inline(never)]
fn push_others<W: BlockView<State = BlockState>>(
a: &mut Pushes<'_, '_, '_>,
world: &W,
options: &Options,
pistons: &mut Pistons,
bx: &Aabb,
slime: bool,
d: [f64; 3],
) {
let mut solids: Vec<Aabb> = Vec::new();
for e in a.others.iter_mut() {
if !e.moved || !search_finds(e.section, bx) || !e.bb.intersects(bx) {
continue;
}
if !e.followed {
pistons.unmodelled = true;
continue;
}
if slime {
continue;
}
let q = e.bb.stretch(d[0], d[1], d[2]).grow(0.25, 0.25, 0.25);
solids.clear();
solids.extend(
a.solids
.iter()
.filter(|s| search_finds(s.1, &q))
.map(|s| s.0),
);
other_push_move(
&mut e.bb,
&mut e.pos,
&mut e.on_ground,
&mut e.in_web,
e.sneaking,
e.step_height,
&solids,
world,
options,
pistons,
d,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
#[test]
fn facts_match_oracle_dump() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.8.9/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["id"].as_u64().unwrap() as u8;
let b = match v["piston"].as_u64().unwrap() {
0 => Behaviour::Normal,
1 => Behaviour::Destroy,
_ => Behaviour::Block,
};
assert!(behaviour(id) == b, "behaviour of {id}");
assert_eq!(
unbreakable(id),
v["unbreakable"].as_bool().unwrap(),
"strength of {id}"
);
assert_eq!(
has_block_entity(id),
v["block_entity"].as_bool().unwrap(),
"block entity of {id}"
);
let air = Block::from_id(id).is_some_and(|b| b.default_state().is_air());
assert_eq!(air, v["air"].as_bool().unwrap(), "air of {id}");
n += 1;
}
assert_eq!(n, 198);
}
#[test]
fn empty_pistons_take_the_plain_tick() {
let mut w = super::super::memory_world();
w.load_chunks(-1, -1, 0, 0);
w.fill_raw([-4, 63, -4], [4, 63, 4], 1 << 4);
let mut a = PlayerState::new([0.5, 64.0, 0.5], 0.0, 0.0);
let mut b = a;
let input = TickInput::default();
let (mut oa, mut ob) = (Packets::new(), Packets::new());
let mut edits = Edits::new();
for _ in 0..20 {
oa.clear();
ob.clear();
super::super::tick_with(&mut a, &input, &w, &Options::default(), &mut oa);
tick_with_pistons(
&mut b,
&input,
&w,
&Options::default(),
&mut Pistons::new(),
&mut ob,
&mut edits,
);
assert_eq!(a, b);
assert_eq!(oa.as_slice(), ob.as_slice());
}
assert!(edits.is_empty());
}
}