use ghast_data::v1_12::{Block, BlockState};
use super::blocks::{
BoxList, BoxSink, actual_shape, add_actual_collision_boxes, is_valid_pos, state_at,
};
use super::ext::PlayerExt;
use super::player::{Options, PlayerState, piston_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]
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]
}
#[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,
actual: u8,
}
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 moving_shape(&self) -> Shape {
if !self.extending && self.source {
Shape::Head {
facing: self.pushed.meta() & 7,
short: false,
}
} else {
Shape::State(self.pushed, self.actual)
}
}
}
#[derive(Clone, Copy)]
enum Shape {
State(BlockState, u8),
Head { facing: Facing, short: bool },
}
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],
];
const HEAD_ARM: [[f64; 6]; 6] = [
[0.375, 0.25, 0.375, 0.625, 1.25, 0.625],
[0.375, -0.25, 0.375, 0.625, 0.75, 0.625],
[0.375, 0.375, 0.25, 0.625, 0.625, 1.25],
[0.375, 0.375, -0.25, 0.625, 0.625, 0.75],
[0.25, 0.375, 0.375, 1.25, 0.625, 0.625],
[-0.25, 0.375, 0.375, 0.75, 0.625, 0.625],
];
const HEAD_ARM_SHORT: [[f64; 6]; 6] = [
[0.375, 0.25, 0.375, 0.625, 1.0, 0.625],
[0.375, 0.0, 0.375, 0.625, 0.75, 0.625],
[0.375, 0.375, 0.25, 0.625, 0.625, 1.0],
[0.375, 0.375, 0.0, 0.625, 0.625, 0.75],
[0.25, 0.375, 0.375, 1.0, 0.625, 0.625],
[0.0, 0.375, 0.375, 0.75, 0.625, 0.625],
];
#[inline]
fn at(b: &[f64; 6], x: i32, y: i32, z: i32) -> Aabb {
let (fx, fy, fz) = (f64::from(x), f64::from(y), f64::from(z));
Aabb::new(
b[0] + fx,
b[1] + fy,
b[2] + fz,
b[3] + fx,
b[4] + fy,
b[5] + fz,
)
}
fn shape_boxes<W: BlockView<State = BlockState>>(
w: &W,
shape: Shape,
pos: [i32; 3],
query: Aabb,
out: &mut BoxList,
) {
match shape {
Shape::Head { facing, short } => {
let f = (facing as usize).min(5);
let arm = if short {
&HEAD_ARM_SHORT[f]
} else {
&HEAD_ARM[f]
};
for b in [&HEAD_PLATE[f], arm] {
let w = at(b, pos[0], pos[1], pos[2]);
if query.intersects(&w) {
out.push(w);
}
}
}
Shape::State(s, actual) => {
let mut sink = BoxSink { query, out };
add_actual_collision_boxes(w, pos[0], pos[1], pos[2], s, actual, &mut sink);
}
}
}
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 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().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;
}
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],
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
}
pub fn tick_blocks<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
let mut a = Actors {
p: None,
others: &mut [],
player_rank: 0,
player_section: None,
};
tick_moving(&mut a, world, time, self, edits);
}
}
pub(super) fn collision_into<W: BlockView<State = BlockState>>(
&self,
w: &W,
pos: [i32; 3],
query: &Aabb,
pushing: Option<Facing>,
out: &mut BoxList,
) {
let Some(m) = self.at(pos) else {
return;
};
if !m.extending && m.source {
let base = BlockState::new(m.pushed.block(), m.pushed.meta() | 8);
shape_boxes(w, Shape::State(base, 0), pos, *query, out);
}
if m.progress >= 1.0 || pushing != Some(m.moves()) {
let shape = if m.source {
Shape::Head {
facing: m.facing,
short: m.extending != (1.0 - m.progress < 0.25),
}
} else {
Shape::State(m.pushed, m.actual)
};
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),
);
let n = out.len();
shape_boxes(w, shape, pos, query.offset(-d, -e, -g), out);
out.offset_from(n, d, e, g);
}
}
}
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,
PushOnly,
}
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
| 199
| 200
| 207
| 217
| 219..=234 => Behaviour::Destroy,
29 | 33 | 34 | 36 | 90 | 119 | 145 | 166 | 209 => Behaviour::Block,
235..=250 => Behaviour::PushOnly,
_ => Behaviour::Normal,
}
}
fn unbreakable(id: u8) -> bool {
matches!(id, 7 | 36 | 90 | 119 | 120 | 137 | 166 | 209..=211 | 255)
}
fn has_block_entity(id: u8) -> bool {
matches!(
id,
23 | 25
| 26
| 36
| 52
| 54
| 61..=63
| 68
| 84
| 116
| 117
| 119
| 130
| 137
| 138
| 140
| 144
| 146
| 149..=151
| 154
| 158
| 176..=178
| 209..=211
| 219..=234
| 255
)
}
#[inline]
fn is_piston(id: u8) -> bool {
id == PISTON || id == STICKY_PISTON
}
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,
actual: u8,
) {
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,
actual,
});
}
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);
if !is_piston(state.block().id()) {
return false;
}
let facing = state.meta() & 7;
if facing > 5 {
return false;
}
let sticky = state.block().id() == STICKY_PISTON;
let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
match action {
0 => {
if !self.move_blocks(pos, facing, true, sticky) {
return true;
}
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);
}
self.set(
pos,
BlockState::new(moving, facing | if sticky { 8 } else { 0 }),
);
self.add_moving(
pos,
BlockState::new(state.block(), data & 15),
facing,
false,
true,
0,
);
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, facing)
&& (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,
piston: Facing,
) -> bool {
let id = b.block().id();
if id == OBSIDIAN || !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 b.meta() & 8 != 0 {
return false;
}
} else {
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(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 states: Vec<BlockState> = h.moved.iter().map(|&m| self.get(m)).collect();
let actuals: Vec<u8> = {
let v = Layered {
w: self.w,
edits: &self.edits[self.start..],
};
h.moved
.iter()
.zip(&states)
.map(|(&m, &s)| actual_shape(&v, m[0], m[1], m[2], s))
.collect()
};
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 (k, &m) in h.moved.iter().enumerate().rev() {
self.set(m, BlockState::AIR);
let dst = step(m, push, 1);
self.set(dst, BlockState::new(moving, facing));
self.add_moving(dst, states[k], facing, extend, false, actuals[k]);
}
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,
true,
0,
);
}
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, self.dir) {
if behaviour(b.block().id()) == Behaviour::Destroy {
self.broken.push(self.to);
return true;
}
return false;
}
if !self.try_move(ov, self.to, self.dir) {
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],
from_dir: Facing,
) -> bool {
let mut b = ov.get(pos);
if b.is_air()
|| !ov.movable(b, pos, self.dir, false, from_dir)
|| 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, 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.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, self.dir) || 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), 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,
input: &TickInput,
world: &W,
options: &Options,
entities: &[Aabb],
pistons: &mut Pistons,
time: i64,
out: &mut Packets,
edits: &mut Edits,
) {
tick_player_among_pistons(p, x, input, world, options, entities, pistons, out);
pistons.tick_after_entities(p, x, world, entities, time, edits);
}
#[allow(clippy::too_many_arguments)]
pub fn tick_player_among_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
x: &mut PlayerExt,
input: &TickInput,
world: &W,
options: &Options,
entities: &[Aabb],
pistons: &Pistons,
out: &mut Packets,
) {
let view = Distinct(world);
tick_with_moving(p, x, input, &view, options, entities, pistons, out);
}
impl Pistons {
#[allow(clippy::too_many_arguments)]
pub fn tick_after_entities<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
x: &mut PlayerExt,
world: &W,
entities: &[Aabb],
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
let mut a = Actors {
p: Some((p, x, entities)),
others: &mut [],
player_rank: 0,
player_section: None,
};
tick_moving(&mut a, world, time, self, edits);
}
}
#[allow(clippy::too_many_arguments)]
pub fn tick_after_entities_among<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
x: &mut PlayerExt,
world: &W,
entities: &[Aabb],
others: &mut [PistonEntity],
player: PlayerPlace,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
let mut a = Actors {
p: Some((p, x, entities)),
others,
player_rank: player.rank,
player_section: Some(player.section),
};
tick_moving(&mut a, world, time, self, edits);
}
}
}
#[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 moved: bool,
pub collidable: bool,
pub pushable: bool,
pub hits_pushable: bool,
pub section: [i32; 3],
pub carry: PistonCarry,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlayerPlace {
pub rank: usize,
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])
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PistonCarry {
delta: [f64; 3],
delta_time: i64,
}
type PlayerRef<'a, 'b> = (&'a mut PlayerState, &'a mut PlayerExt, &'b [Aabb]);
struct Actors<'a, 'b, 'c> {
p: Option<PlayerRef<'a, 'b>>,
others: &'c mut [PistonEntity],
player_rank: usize,
player_section: Option<[i32; 3]>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Actor {
Player,
Other(usize),
}
impl Actors<'_, '_, '_> {
fn order(&self) -> impl Iterator<Item = Actor> + use<> {
let n = self.others.len();
let rank = self.p.as_ref().map(|_| self.player_rank.min(n));
(0..=n).filter_map(move |k| match rank {
Some(r) if k == r => Some(Actor::Player),
Some(r) if k > r => Some(Actor::Other(k - 1)),
_ if k < n => Some(Actor::Other(k)),
_ => None,
})
}
fn bb(&self, a: Actor) -> Aabb {
match a {
Actor::Player => self.p.as_ref().expect("player").0.bb,
Actor::Other(k) => self.others[k].bb,
}
}
fn found(&self, a: Actor, q: &Aabb) -> bool {
match a {
Actor::Player => self.player_section.is_none_or(|s| search_finds(s, q)),
Actor::Other(k) => search_finds(self.others[k].section, q),
}
}
fn movable(&self, a: Actor) -> bool {
match a {
Actor::Player => !self.p.as_ref().expect("player").0.spectator,
Actor::Other(k) => self.others[k].moved,
}
}
}
fn tick_moving<W: BlockView<State = BlockState>>(
a: &mut Actors<'_, '_, '_>,
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 || !(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 {
m.removed = true;
let m = *m;
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 {
let f = m.progress + 0.5;
let m = *m;
if a.p.is_some() {
let view = Layered {
w: world,
edits: &edits[start..],
};
push(a, &Distinct(&view), time, pistons, &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 origin_boxes<W: BlockView<State = BlockState>>(w: &W, shape: Shape, out: &mut BoxList) {
shape_boxes(w, shape, [0, 0, 0], Aabb::FULL, out);
}
fn swept_face(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 {
let positive = dir & 1 == 1;
match axis(dir) {
2 => {
if positive {
b.max_x - e.min_x
} else {
e.max_x - b.min_x
}
}
1 => {
if positive {
b.max_z - e.min_z
} else {
e.max_z - b.min_z
}
}
_ => {
if positive {
b.max_y - e.min_y
} else {
e.max_y - b.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),
)
}
fn push<W: BlockView<State = BlockState>>(
a: &mut Actors<'_, '_, '_>,
world: &W,
time: i64,
pistons: &mut Pistons,
m: &MovingBlock,
f: f32,
) {
let dir = m.moves();
let d = f64::from(f - m.progress);
let mut list = BoxList::new();
origin_boxes(world, m.moving_shape(), &mut list);
if list.is_empty() {
return;
}
let o = offset(m.facing);
let s = f64::from(m.shift(m.progress));
let place = |b: &Aabb| {
b.offset(
f64::from(m.pos[0]) + s * f64::from(o[0]),
f64::from(m.pos[1]) + s * f64::from(o[1]),
f64::from(m.pos[2]) + s * f64::from(o[2]),
)
};
let mut hull = Aabb::FULL;
for b in list.as_slice() {
hull = union(&hull, b);
}
let bx = place(&hull);
let query = union(&swept_face(&bx, dir, d), &bx);
let members: Vec<Actor> = a
.order()
.filter(|&x| a.movable(x) && a.found(x, &query) && a.bb(x).intersects(&query))
.collect();
let od = offset(dir);
for x in members {
if m.pushed.block().id() == SLIME
&& let Actor::Player = x
{
let k = axis_index(dir);
a.p.as_mut().expect("player").0.vel[k] = f64::from(od[k]);
}
let mut e: f64 = 0.0;
for b in list.as_slice() {
let b2 = swept_face(&place(b), dir, d);
let bb = a.bb(x);
if b2.intersects(&bb) {
e = e.max(reach(&b2, dir, &bb));
if e >= d {
break;
}
}
}
#[allow(clippy::neg_cmp_op_on_partial_ord)]
if !(e <= 0.0) {
let e = e.min(d) + 0.01;
move_by_piston(a, x, world, time, pistons, dir, dir, e);
if !m.extending && m.source {
pull_back(a, x, world, time, pistons, m, dir, d);
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn pull_back<W: BlockView<State = BlockState>>(
a: &mut Actors<'_, '_, '_>,
x: Actor,
world: &W,
time: i64,
pistons: &mut Pistons,
m: &MovingBlock,
dir: Facing,
d: f64,
) {
let bb = a.bb(x);
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 e = 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 f = reach(&cell, back, &inter) + 0.01;
if (e - f).abs() < 0.01 {
let e = e.min(d) + 0.01;
move_by_piston(a, x, world, time, pistons, back, dir, e);
}
}
fn piston_budget(
delta: &mut [f64; 3],
delta_time: &mut i64,
time: i64,
mut d: [f64; 3],
) -> Option<[f64; 3]> {
if time != *delta_time {
*delta = [0.0; 3];
*delta_time = time;
}
let k = [0, 1, 2].into_iter().find(|&k| d[k] != 0.0)?;
let v = (d[k] + delta[k]).clamp(-0.51, 0.51);
d[k] = v - delta[k];
delta[k] = v;
if d[k].abs() <= f64::from(1.0e-5f32) {
return None;
}
Some(d)
}
#[allow(clippy::too_many_arguments)]
fn move_by_piston<W: BlockView<State = BlockState>>(
a: &mut Actors<'_, '_, '_>,
who: Actor,
world: &W,
time: i64,
pistons: &mut Pistons,
dir: Facing,
pushing: Facing,
e: f64,
) {
let o = offset(dir);
let d = [
e * f64::from(o[0]),
e * f64::from(o[1]),
e * f64::from(o[2]),
];
match who {
Actor::Player => {
let collidable = a.others.iter().any(|o| o.collidable);
let mut boxes: Vec<Aabb> = Vec::new();
let (p, x, ents) = a.p.as_mut().expect("player");
let ents: &[Aabb] = if collidable {
let q = p.bb.stretch(d[0], d[1], d[2]).grow(0.25, 0.25, 0.25);
boxes.extend_from_slice(ents);
boxes.extend(
a.others
.iter()
.filter(|o| o.collidable && search_finds(o.section, &q))
.map(|o| o.bb),
);
&boxes
} else {
ents
};
if p.no_clip {
piston_move(p, x, ents, world, pistons, pushing, d);
return;
}
let Some(d) = piston_budget(&mut pistons.delta, &mut pistons.delta_time, time, d)
else {
return;
};
piston_move(p, x, ents, world, pistons, pushing, d);
}
Actor::Other(k) => {
let mut o = a.others[k];
let Some(d) = piston_budget(&mut o.carry.delta, &mut o.carry.delta_time, time, d)
else {
a.others[k] = o;
return;
};
let player_pushable = a.p.as_ref().is_some_and(|(p, _, _)| {
!p.spectator
&& !super::player::climbing_at(
world,
crate::math::floor(p.pos[0]),
crate::math::floor(p.bb.min_y),
crate::math::floor(p.pos[2]),
)
});
let q = o.bb.stretch(d[0], d[1], d[2]).grow(0.25, 0.25, 0.25);
let boxes: Vec<Aabb> = a
.order()
.filter(|&b| a.found(b, &q))
.filter(|&b| match b {
Actor::Player => o.hits_pushable && player_pushable,
Actor::Other(j) => {
j != k && {
let t = &a.others[j];
t.collidable || (o.hits_pushable && t.pushable)
}
}
})
.map(|b| a.bb(b))
.collect();
super::player::other_piston_move(
&mut o.bb,
&mut o.pos,
&mut o.on_ground,
&mut o.in_web,
o.step_height,
&boxes,
world,
pistons,
pushing,
d,
);
a.others[k] = o;
}
}
}
#[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.12.2/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["raw"].as_u64().unwrap() >> 4) as u8;
let b = match v["piston"].as_u64().unwrap() {
0 => Behaviour::Normal,
1 => Behaviour::Destroy,
2 => Behaviour::Block,
_ => Behaviour::PushOnly,
};
assert!(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_eq!(id == 0, v["air"].as_bool().unwrap(), "air of {id}");
n += 1;
}
assert!(n > 1000);
}
}