use super::super::collide::model_offset;
use super::super::moving::{MovingShapes, Part, union as union_shape};
use super::super::piston_facts::UPDATE_CLASSES;
use super::super::piston_shapes::SOURCE_SHAPES;
use super::super::player::{move_player_by_piston, tick_among_moving};
use super::super::rules::Rules;
use super::super::rules::shared::state_flags as sf;
use super::super::{LevelInfo, PlayerExt, PlayerState, Surroundings};
use super::{
CLIENT_HOLD, FACING_NAMES, Facing, MAX_DEPTH, PUSH_LIMIT, UPDATE_SHAPE_ORDER, axis, axis_index,
bool_str, clockwise, counter_clockwise, hash_map_order, intersect, offset, opposite,
piston_budget, reach, search_finds, step, stretch, union,
};
use crate::input::{Packets, TickInput};
use crate::math::{Aabb, BoxOps};
use crate::world::{BlockView, WorldBorder};
use ver::{Block, BlockState, Property};
fn facing_of(s: BlockState) -> Option<Facing> {
let v = s.get(Property::Facing)?;
FACING_NAMES
.iter()
.position(|n| *n == v)
.map(|i| i as Facing)
}
fn with(s: BlockState, p: Property, v: &str) -> BlockState {
s.with(p, v).unwrap_or(s)
}
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 Reaction {
Normal,
Destroy,
Block,
Ignore,
PushOnly,
}
fn reaction(b: Block) -> Reaction {
match FACTS[usize::from(b.id())] & 7 {
1 => Reaction::Destroy,
2 => Reaction::Block,
3 => Reaction::Ignore,
4 => Reaction::PushOnly,
_ => Reaction::Normal,
}
}
fn unbreakable(b: Block) -> bool {
FACTS[usize::from(b.id())] & 8 != 0
}
fn has_block_entity(b: Block) -> bool {
FACTS[usize::from(b.id())] & 16 != 0
}
fn update_class(b: Block) -> &'static str {
UPDATE_CLASSES[usize::from(UPDATE[usize::from(b.id())])]
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
Inert,
Fence,
Bars,
Wall,
Stairs,
Gate,
Snowy,
Carpet,
DeadCoral,
DeadWallFan,
Mushroom,
Other,
}
fn kind(b: Block) -> Kind {
match update_class(b) {
"FenceBlock" => Kind::Fence,
"IronBarsBlock" => Kind::Bars,
"WallBlock" => Kind::Wall,
"StairBlock" => Kind::Stairs,
"FenceGateBlock" => Kind::Gate,
"SnowyBlock" => Kind::Snowy,
"CarpetBlock" => Kind::Carpet,
"BaseCoralPlantTypeBlock" => Kind::DeadCoral,
"BaseCoralWallFanBlock" => Kind::DeadWallFan,
"HugeMushroomBlock" => Kind::Mushroom,
"BlockBehaviour"
| "AmethystClusterBlock"
| "BannerBlock"
| "BarrierBlock"
| "BasePressurePlateBlock"
| "BaseRailBlock"
| "BaseTorchBlock"
| "BeehiveBlock"
| "BigDripleafStemBlock"
| "BrushableBlock"
| "BubbleColumnBlock"
| "CactusBlock"
| "CakeBlock"
| "CandleBlock"
| "CandleCakeBlock"
| "CeilingHangingSignBlock"
| "ChainBlock"
| "ChorusFlowerBlock"
| "CocoaBlock"
| "ComparatorBlock"
| "ConduitBlock"
| "CopperGolemStatueBlock"
| "CoralBlock"
| "CoralFanBlock"
| "CoralPlantBlock"
| "CoralWallFanBlock"
| "CreakingHeartBlock"
| "DecoratedPotBlock"
| "DirtPathBlock"
| "DoublePlantBlock"
| "DriedGhastBlock"
| "EnderChestBlock"
| "FaceAttachedHorizontalDirectionalBlock"
| "FallingBlock"
| "FarmlandBlock"
| "FlowerPotBlock"
| "FrogspawnBlock"
| "HangingRootsBlock"
| "HeavyCoreBlock"
| "LadderBlock"
| "LanternBlock"
| "LeavesBlock"
| "LightBlock"
| "LightningRodBlock"
| "LiquidBlock"
| "MangrovePropaguleBlock"
| "MangroveRootsBlock"
| "NetherPortalBlock"
| "ObserverBlock"
| "PistonHeadBlock"
| "RedstoneWallTorchBlock"
| "ScaffoldingBlock"
| "SculkSensorBlock"
| "SculkShriekerBlock"
| "SeaPickleBlock"
| "SeagrassBlock"
| "ShelfBlock"
| "SlabBlock"
| "SmallDripleafBlock"
| "SnowLayerBlock"
| "SporeBlossomBlock"
| "StandingSignBlock"
| "SugarCaneBlock"
| "TrapDoorBlock"
| "TripWireHookBlock"
| "VegetationBlock"
| "WallBannerBlock"
| "WallHangingSignBlock"
| "WallSignBlock"
| "WallTorchBlock"
| "WaterloggedTransparentBlock" => Kind::Inert,
_ => Kind::Other,
}
}
fn tag(b: Block, bit: u8) -> bool {
TAGS[usize::from(b.id())] & bit != 0
}
fn is_wall(b: Block) -> bool {
kind(b) == Kind::Wall
}
fn is_stairs(s: BlockState) -> bool {
kind(s.block()) == Kind::Stairs
}
fn side_property(d: Facing) -> Property {
match d {
2 => Property::North,
3 => Property::South,
4 => Property::West,
_ => Property::East,
}
}
const WALL_SIDES: [Property; 4] = [
Property::North,
Property::East,
Property::South,
Property::West,
];
fn gate_connects(n: BlockState, side: Facing) -> bool {
kind(n.block()) == Kind::Gate && facing_of(n).is_some_and(|f| axis(f) == axis(clockwise(side)))
}
fn fence_connects(fence: Block, n: BlockState, solid: bool, side: Facing) -> bool {
let b = n.block();
let same = tag(b, 2) && tag(b, 4) == tag(fence, 4);
(!tag(b, 16) && solid) || same || gate_connects(n, side)
}
fn bars_connect(n: BlockState, solid: bool) -> bool {
let b = n.block();
(!tag(b, 16) && solid) || kind(b) == Kind::Bars || tag(b, 1)
}
fn wall_connects(n: BlockState, solid: bool, side: Facing) -> bool {
let b = n.block();
tag(b, 1) || (!tag(b, 16) && solid) || kind(b) == Kind::Bars || gate_connects(n, side)
}
fn moving_state(facing: Facing, sticky: bool) -> BlockState {
let s = with(
Block::MOVING_PISTON.default_state(),
Property::Facing,
FACING_NAMES[facing as usize],
);
if sticky {
with(s, Property::Type, "sticky")
} else {
s
}
}
#[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,
}
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(),
Property::Facing,
FACING_NAMES[f as usize],
);
h = with(
h,
Property::Short,
if self.progress > 0.25 {
"true"
} else {
"false"
},
);
if self.pushed.block() == Block::STICKY_PISTON {
h = with(h, Property::Type, "sticky");
}
h
} else {
self.pushed
}
}
fn place(&self, b: &Aabb) -> Aabb {
let d = f64::from(self.shift(self.progress));
let o = offset(self.facing);
b.offset(
f64::from(self.pos[0]) + d * f64::from(o[0]),
f64::from(self.pos[1]) + d * f64::from(o[1]),
f64::from(self.pos[2]) + d * f64::from(o[2]),
)
}
}
fn local_boxes(s: BlockState, pos: [i32; 3]) -> Option<Vec<Aabb>> {
let p = R::phys(s);
let f = p.flags();
if f & sf::FULL_CUBE != 0 {
return Some(vec![Aabb::new(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)]);
}
let shape = if f & sf::CONTEXT != 0 {
s.voxel_shape()
} else if f & sf::EMPTY != 0 {
return None;
} else {
s.voxel_shape()
};
if shape.empty {
return None;
}
let k = if f & sf::OFFSET != 0 {
model_offset(R::offset(s), pos[0], pos[2])
} else {
[0.0; 3]
};
Some(
shape
.boxes
.iter()
.map(|b| {
if f & sf::OFFSET != 0 {
Aabb::new(
b.min_x + k[0],
b.min_y + k[1],
b.min_z + k[2],
b.max_x + k[0],
b.max_y + k[1],
b.max_z + k[2],
)
} else {
*b
}
})
.collect(),
)
}
fn hull(boxes: &[Aabb]) -> Aabb {
let mut h = boxes[0];
for b in &boxes[1..] {
h = union(&h, b);
}
h
}
pub type Edits = Vec<([i32; 3], BlockState)>;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Pistons {
slots: Vec<Option<MovingBlock>>,
delta: [f64; 3],
delta_time: i64,
unmodelled: bool,
player_resectioned: bool,
}
impl Pistons {
#[must_use]
pub const fn new() -> Pistons {
Pistons {
slots: Vec::new(),
delta: [0.0; 3],
delta_time: 0,
unmodelled: false,
player_resectioned: false,
}
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.slots.is_empty()
}
pub fn take_unmodelled(&mut self) -> bool {
std::mem::take(&mut self.unmodelled)
}
pub fn take_player_resectioned(&mut self) -> bool {
std::mem::take(&mut self.player_resectioned)
}
pub fn iter(&self) -> impl Iterator<Item = &MovingBlock> {
self.slots.iter().flatten()
}
#[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.iter().find(|b| b.pos == pos)
}
fn index_at(&self, pos: [i32; 3]) -> Option<usize> {
self.slots
.iter()
.position(|b| b.is_some_and(|b| b.pos == pos))
}
pub fn clear(&mut self) {
self.slots.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.slots.retain(|b| b.is_some_and(|b| 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.slots[i] = None;
}
}
pub fn chunk_replaced(&mut self, cx: i32, cz: i32) {
self.slots
.retain(|b| b.is_some_and(|b| !(b.pos[0] >> 4 == cx && b.pos[2] >> 4 == cz)));
}
fn add(&mut self, b: MovingBlock) {
match self.index_at(b.pos) {
Some(i) => self.slots[i] = Some(b),
None => self.slots.push(Some(b)),
}
}
fn remove_at(&mut self, pos: [i32; 3]) {
if let Some(i) = self.index_at(pos) {
self.slots[i] = None;
}
}
pub fn block_event<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
level: &LevelInfo,
pos: [i32; 3],
action: u8,
data: u8,
edits: &mut Edits,
) -> bool {
let start = edits.len();
let mut ov = Overlay {
w: world,
level: *level,
edits,
start,
pistons: self,
};
ov.on_event(pos, action, data)
}
pub fn tick_blocks<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
level: &LevelInfo,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
let mut a = Actors {
p: None,
others: &mut [],
player_rank: 0,
};
tick_moving(&mut a, world, level, time, self, edits);
}
}
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() {
let level = p.level;
let mut a = Actors {
p: Some((p, x, around)),
others: &mut [],
player_rank: 0,
};
tick_moving(&mut a, world, &level, time, self, edits);
}
}
fn shapes(&self, pushing: Option<Facing>) -> MovingShapes {
let mut out = MovingShapes::new();
for m in self.iter() {
add_shape(&mut out, m, pushing);
}
out
}
}
fn add_shape(out: &mut MovingShapes, m: &MovingBlock, pushing: Option<Facing>) {
let base_shape = !m.extending && m.source && is_piston(m.pushed.block());
if m.progress < 1.0 && pushing == Some(m.moves()) {
if base_shape {
let s = with(m.pushed, Property::Extended, "true");
if let Some(boxes) = local_boxes(s, m.pos)
&& let Some(part) = union_shape(boxes.into_iter())
{
out.push(m.pos, part);
}
}
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];
if t.empty {
return;
}
let full = t.sizes == [1, 1, 1] && t.cells == [1];
out.push(m.pos, if full { Part::Cube } else { Part::Table(t) });
return;
}
}
let state = if m.source {
let h = with(
Block::PISTON_HEAD.default_state(),
Property::Facing,
FACING_NAMES[m.facing as usize],
);
let short = m.extending != (1.0 - m.progress < 0.25);
with(h, Property::Short, if short { "true" } else { "false" })
} 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),
);
let Some(boxes) = local_boxes(state, m.pos) else {
return;
};
let moved = boxes.into_iter().map(|b| {
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(part) = union_shape(moved) {
out.push(m.pos, part);
}
}
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,
level: LevelInfo,
edits: &'a mut Edits,
start: usize,
pistons: &'a mut Pistons,
}
impl<W: BlockView<State = BlockState>> Overlay<'_, W> {
fn valid(&self, p: [i32; 3]) -> bool {
p[1] >= self.level.min_y
&& p[1] < self.level.min_y + self.level.height
&& (-30_000_000..30_000_000).contains(&p[0])
&& (-30_000_000..30_000_000).contains(&p[2])
}
fn get(&self, p: [i32; 3]) -> BlockState {
if p[1] < self.level.min_y || p[1] >= self.level.min_y + self.level.height {
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, flags: u32, depth: u32) {
if !self.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() != s.block() && old.block() == Block::MOVING_PISTON {
self.pistons.remove_at(p);
}
self.edits.push((p, s));
if flags & 16 == 0 && depth > 0 {
if old.block() == Block::REDSTONE_WIRE || s.block() == Block::REDSTONE_WIRE {
self.pistons.unmodelled = true;
}
self.update_neighbours(p, s, flags & !33, depth - 1);
}
}
fn update_neighbours(&mut self, p: [i32; 3], s: BlockState, flags: u32, depth: u32) {
for d in UPDATE_SHAPE_ORDER {
let q = step(p, d, 1);
let n = self.get(q);
if flags & 128 != 0 && n.block() == Block::REDSTONE_WIRE {
continue;
}
let new = match self.shape_update(n, opposite(d), s, q, p) {
Ok(v) => v,
Err(v) => {
self.pistons.unmodelled = true;
v
}
};
if new != n && !new.is_air() {
self.set(q, new, flags & !32, depth);
}
}
}
fn neighbour_shapes(&mut self, s: BlockState, p: [i32; 3]) -> BlockState {
let mut out = s;
for d in UPDATE_SHAPE_ORDER {
let q = step(p, d, 1);
let n = self.get(q);
out = match self.shape_update(out, d, n, p, q) {
Ok(v) => v,
Err(v) => {
self.pistons.unmodelled = true;
v
}
};
}
out
}
fn shape_update(
&self,
s: BlockState,
dir: Facing,
n: BlockState,
pos: [i32; 3],
npos: [i32; 3],
) -> Result<BlockState, BlockState> {
let horizontal = dir >= 2;
match kind(s.block()) {
Kind::Inert => Ok(s),
Kind::Other => Err(s),
Kind::Fence if horizontal => {
let solid = self.side_solid(npos, n, opposite(dir));
let c = fence_connects(s.block(), n, solid, opposite(dir));
Ok(with(s, side_property(dir), bool_str(c)))
}
Kind::Bars if horizontal => {
let solid = self.side_solid(npos, n, opposite(dir));
Ok(with(
s,
side_property(dir),
bool_str(bars_connect(n, solid)),
))
}
Kind::Gate => {
let f = facing_of(s).ok_or(s)?;
if axis(clockwise(f)) != axis(dir) {
return Ok(s);
}
let w =
is_wall(n.block()) || is_wall(self.get(step(pos, opposite(dir), 1)).block());
Ok(with(s, Property::InWall, bool_str(w)))
}
Kind::Snowy if dir == 1 => Ok(with(s, Property::Snowy, bool_str(tag(n.block(), 32)))),
Kind::Stairs if horizontal => Ok(with(s, Property::Shape, self.stair_shape(s, pos))),
Kind::Carpet => Ok(if self.get(step(pos, 0, 1)).is_air() {
BlockState::AIR
} else {
s
}),
Kind::DeadCoral if dir == 0 => {
let below = step(pos, 0, 1);
Ok(if self.side_solid(below, self.get(below), 1) {
s
} else {
BlockState::AIR
})
}
Kind::DeadWallFan => {
let f = facing_of(s).ok_or(s)?;
if opposite(dir) != f {
return Ok(s);
}
let behind = step(pos, opposite(f), 1);
Ok(if self.side_solid(behind, self.get(behind), f) {
s
} else {
BlockState::AIR
})
}
Kind::Mushroom => Ok(if n.block() == s.block() {
with(s, side_property(dir), "false")
} else {
s
}),
Kind::Wall if dir != 0 => {
let mut c = [false; 4];
for (k, p) in WALL_SIDES.iter().enumerate() {
c[k] = s.get(*p) != Some("none");
}
let above = if dir == 1 {
(npos, n)
} else {
let k = WALL_SIDES
.iter()
.position(|w| *w == side_property(dir))
.expect("horizontal");
let solid = self.side_solid(npos, n, opposite(dir));
c[k] = wall_connects(n, solid, opposite(dir));
let up = step(pos, 1, 1);
(up, self.get(up))
};
Ok(self.wall_state(s, above.0, above.1, c))
}
_ => Ok(s),
}
}
fn moving_part(&self, p: [i32; 3]) -> Option<Part> {
let m = self.pistons.at(p)?;
let mut out = MovingShapes::new();
add_shape(&mut out, m, None);
out.at(p).next().cloned()
}
fn side_solid(&self, p: [i32; 3], s: BlockState, face: Facing) -> bool {
if s.block() == Block::MOVING_PISTON {
return self.moving_part(p).is_some_and(|part| {
super::face_covers(&super::part_view(&part), face, [0.0, 0.0, 1.0, 1.0], true)
});
}
let ph = R::phys(s);
match face {
2 => ph.flags() & sf::STURDY_NORTH != 0,
5 => ph.flags() & (sf::STURDY_NORTH << 1) != 0,
3 => ph.flags() & (sf::STURDY_NORTH << 2) != 0,
4 => ph.flags() & (sf::STURDY_NORTH << 3) != 0,
_ => {
if ph.flags() & sf::FULL_CUBE != 0 {
return true;
}
if ph.flags() & sf::EMPTY != 0 && ph.flags() & sf::CONTEXT == 0 {
return false;
}
let r = s.voxel_shape();
!r.empty
&& super::face_covers(&super::table_view(r), face, [0.0, 0.0, 1.0, 1.0], true)
}
}
}
fn down_face_covers(&self, p: [i32; 3], s: BlockState, rect: [f64; 4]) -> bool {
if s.block() == Block::MOVING_PISTON {
return self
.moving_part(p)
.is_some_and(|part| super::face_covers(&super::part_view(&part), 0, rect, false));
}
let ph = R::phys(s);
if ph.flags() & sf::FULL_CUBE != 0 {
return true;
}
if ph.flags() & sf::EMPTY != 0 && ph.flags() & sf::CONTEXT == 0 {
return false;
}
let r = s.voxel_shape();
!r.empty && super::face_covers(&super::table_view(r), 0, rect, false)
}
fn wall_state(
&self,
s: BlockState,
above_pos: [i32; 3],
above: BlockState,
c: [bool; 4],
) -> BlockState {
let mut out = s;
let mut tall = [false; 4];
for k in 0..4 {
let value = if c[k] {
tall[k] = self.down_face_covers(
above_pos,
above,
super::sixteenths(super::TALL_SIDES[k]),
);
if tall[k] { "tall" } else { "low" }
} else {
"none"
};
out = with(out, WALL_SIDES[k], value);
}
let up = if is_wall(above.block()) && above.get(Property::Up) == Some("true") {
true
} else {
let [n, e, so, w] = c.map(|x| !x);
if (n && so && w && e) || n != so || w != e {
true
} else if (tall[0] && tall[2]) || (tall[1] && tall[3]) {
false
} else {
tag(above.block(), 8)
|| self.down_face_covers(above_pos, above, super::sixteenths(super::TALL_POST))
}
};
with(out, Property::Up, bool_str(up))
}
fn stair_shape(&self, s: BlockState, pos: [i32; 3]) -> &'static str {
let half = s.get(Property::Half);
let Some(f) = facing_of(s) else {
return "straight";
};
let different = |d: Facing| {
let o = self.get(step(pos, d, 1));
!is_stairs(o) || facing_of(o) != Some(f) || o.get(Property::Half) != half
};
let front = self.get(step(pos, f, 1));
if is_stairs(front)
&& front.get(Property::Half) == half
&& let Some(d2) = facing_of(front)
&& axis(d2) != axis(f)
&& different(opposite(d2))
{
return if d2 == counter_clockwise(f) {
"outer_left"
} else {
"outer_right"
};
}
let back = self.get(step(pos, opposite(f), 1));
if is_stairs(back)
&& back.get(Property::Half) == half
&& let Some(d3) = facing_of(back)
&& axis(d3) != axis(f)
&& different(d3)
{
return if d3 == counter_clockwise(f) {
"inner_left"
} else {
"inner_right"
};
}
"straight"
}
fn remove(&mut self, p: [i32; 3]) {
let s = self.get(p);
if R::phys(s).fluid() != 0 {
self.pistons.unmodelled = true;
}
self.set(p, BlockState::AIR, 3, MAX_DEPTH);
}
fn add_moving(
&mut self,
pos: [i32; 3],
pushed: BlockState,
facing: Facing,
extending: bool,
source: bool,
) {
if !self.valid(pos) || self.get(pos).block() != Block::MOVING_PISTON {
return;
}
self.pistons.add(MovingBlock {
pos,
pushed,
facing,
extending,
source,
progress: 0.0,
last_progress: 0.0,
hold: 0,
});
}
fn finish(&mut self, pos: [i32; 3]) {
let Some(i) = self.pistons.index_at(pos) else {
return;
};
let Some(b) = self.pistons.slots[i] else {
return;
};
self.pistons.slots[i] = None;
if self.get(b.pos).block() == Block::MOVING_PISTON {
let s = if b.source {
BlockState::AIR
} else {
self.neighbour_shapes(b.pushed, b.pos)
};
self.set(b.pos, s, 3, MAX_DEPTH);
}
}
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, Property::Extended, "true"), 67, MAX_DEPTH);
}
1 | 2 => {
if self.pistons.index_at(step(pos, facing, 1)).is_some() {
self.finish(step(pos, facing, 1));
}
let moving = moving_state(facing, sticky);
self.set(pos, moving, 276, MAX_DEPTH);
let base = with(
state.block().default_state(),
Property::Facing,
FACING_NAMES[(data & 7) as usize % 6],
);
self.add_moving(pos, base, facing, false, true);
self.update_neighbours(pos, moving, 2, MAX_DEPTH);
if sticky {
let p2 = step(pos, facing, 2);
let b = self.get(p2);
let mut piece = false;
if b.block() == Block::MOVING_PISTON
&& let Some(i) = self.pistons.index_at(p2)
&& let Some(m) = self.pistons.slots[i]
&& m.facing == facing
&& m.extending
{
self.finish(p2);
piece = true;
}
if !piece {
if action != 1
|| b.is_air()
|| !self.pushable(b, p2, opposite(facing), false, facing)
|| (reaction(b.block()) != Reaction::Normal && !is_piston(b.block()))
{
self.remove(step(pos, facing, 1));
} else {
self.move_blocks(pos, facing, false, sticky);
}
}
} else {
self.remove(step(pos, facing, 1));
}
}
_ => {}
}
true
}
fn pushable(
&self,
b: BlockState,
p: [i32; 3],
dir: Facing,
can_break: bool,
piston: Facing,
) -> bool {
let max_y = self.level.min_y + self.level.height - 1;
if p[1] < self.level.min_y
|| p[1] > max_y
|| !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
|| blk == Block::REINFORCED_DEEPSLATE
{
return false;
}
if (dir == 0 && p[1] == self.level.min_y) || (dir == 1 && p[1] == max_y) {
return false;
}
if is_piston(blk) {
if b.get(Property::Extended) == Some("true") {
return false;
}
} else {
if unbreakable(blk) {
return false;
}
match reaction(blk) {
Reaction::Block => return false,
Reaction::Destroy => return can_break,
Reaction::PushOnly => return dir == piston,
Reaction::Normal | Reaction::Ignore => {}
}
}
!has_block_entity(blk)
}
fn move_blocks(&mut self, pos: [i32; 3], facing: Facing, extend: bool, sticky: bool) -> bool {
let arm = step(pos, facing, 1);
if !extend && self.get(arm).block() == Block::PISTON_HEAD {
self.set(arm, BlockState::AIR, 276, MAX_DEPTH);
}
let mut h = Resolver::new(pos, facing, extend);
if !h.resolve(self) {
return false;
}
let states: Vec<BlockState> = h.push.iter().map(|&m| self.get(m)).collect();
let mut vacated: Vec<([i32; 3], BlockState)> =
h.push.iter().copied().zip(states.iter().copied()).collect();
let dir = if extend { facing } else { opposite(facing) };
for &b in h.destroy.iter().rev() {
self.set(b, BlockState::AIR, 18, MAX_DEPTH);
}
for (k, &m) in h.push.iter().enumerate().rev() {
let dst = step(m, dir, 1);
vacated.retain(|v| v.0 != dst);
self.set(dst, moving_state(facing, false), 324, MAX_DEPTH);
self.add_moving(dst, states[k], facing, extend, false);
}
if extend {
vacated.retain(|v| v.0 != arm);
self.set(arm, moving_state(facing, sticky), 324, MAX_DEPTH);
let mut head = with(
Block::PISTON_HEAD.default_state(),
Property::Facing,
FACING_NAMES[facing as usize],
);
if sticky {
head = with(head, Property::Type, "sticky");
}
self.add_moving(arm, head, facing, true, true);
}
let order = hash_map_order(&h.push, &vacated).unwrap_or_else(|| {
self.pistons.unmodelled = true;
(0..vacated.len()).collect()
});
for &k in &order {
self.set(vacated[k].0, BlockState::AIR, 82, MAX_DEPTH);
}
for &k in &order {
if vacated[k].1.block() == Block::REDSTONE_WIRE {
self.pistons.unmodelled = true;
}
self.update_neighbours(vacated[k].0, BlockState::AIR, 2, MAX_DEPTH);
}
for &b in &h.destroy {
if self.get(b).block() == Block::REDSTONE_WIRE {
self.pistons.unmodelled = true;
}
}
true
}
}
struct Resolver {
from: [i32; 3],
start: [i32; 3],
motion: Facing,
piston: Facing,
extend: bool,
push: Vec<[i32; 3]>,
destroy: Vec<[i32; 3]>,
}
impl Resolver {
fn new(pos: [i32; 3], facing: Facing, extend: bool) -> Resolver {
let (motion, start) = if extend {
(facing, step(pos, facing, 1))
} else {
(opposite(facing), step(pos, facing, 2))
};
Resolver {
from: pos,
start,
motion,
piston: facing,
extend,
push: Vec::new(),
destroy: Vec::new(),
}
}
fn resolve<W: BlockView<State = BlockState>>(&mut self, ov: &Overlay<'_, W>) -> bool {
self.push.clear();
self.destroy.clear();
let b = ov.get(self.start);
if !ov.pushable(b, self.start, self.motion, false, self.piston) {
if self.extend && reaction(b.block()) == Reaction::Destroy {
self.destroy.push(self.start);
return true;
}
return false;
}
if !self.line(ov, self.start, self.motion) {
return false;
}
let mut i = 0;
while i < self.push.len() {
let p = self.push[i];
if is_sticky_block(ov.get(p).block()) && !self.branches(ov, p) {
return false;
}
i += 1;
}
true
}
fn line<W: BlockView<State = BlockState>>(
&mut self,
ov: &Overlay<'_, W>,
start: [i32; 3],
dir: Facing,
) -> bool {
let mut b = ov.get(start);
if b.is_air()
|| !ov.pushable(b, start, self.motion, false, dir)
|| start == self.from
|| self.push.contains(&start)
{
return true;
}
let back = opposite(self.motion);
let mut count = 1usize;
if count + self.push.len() > PUSH_LIMIT {
return false;
}
while is_sticky_block(b.block()) {
let bp = step(start, back, count as i32);
let prev = b.block();
b = ov.get(bp);
if b.is_air()
|| !stuck(prev, b.block())
|| !ov.pushable(b, bp, self.motion, false, back)
|| bp == self.from
{
break;
}
count += 1;
if count + self.push.len() > PUSH_LIMIT {
return false;
}
}
let mut added = 0usize;
for k in (0..count).rev() {
self.push.push(step(start, back, k as i32));
added += 1;
}
let mut i = 1;
loop {
let bp = step(start, self.motion, i);
if let Some(c) = self.push.iter().position(|&p| p == bp) {
self.reorder(added, c);
for j in 0..=c + added {
let p = self.push[j];
if is_sticky_block(ov.get(p).block()) && !self.branches(ov, p) {
return false;
}
}
return true;
}
let b = ov.get(bp);
if b.is_air() {
return true;
}
if !ov.pushable(b, bp, self.motion, true, self.motion) || bp == self.from {
return false;
}
if reaction(b.block()) == Reaction::Destroy {
self.destroy.push(bp);
return true;
}
if self.push.len() >= PUSH_LIMIT {
return false;
}
self.push.push(bp);
added += 1;
i += 1;
}
}
fn reorder(&mut self, added: usize, at: usize) {
let n = self.push.len();
let mut v = Vec::with_capacity(n);
v.extend_from_slice(&self.push[..at]);
v.extend_from_slice(&self.push[n - added..]);
v.extend_from_slice(&self.push[at..n - added]);
self.push = v;
}
fn branches<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.line(ov, q, d) {
return false;
}
}
}
true
}
}
#[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 shapes = pistons.shapes(None);
tick_among_moving::<R, W>(p, x, around, input, world, &shapes, out);
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PistonEntity {
pub bb: Aabb,
pub pos: [f64; 3],
pub local: Aabb,
pub snaps: bool,
pub on_ground: bool,
pub supported_by: Option<[i32; 3]>,
pub step_height: f32,
pub moved: bool,
pub normal: bool,
pub collidable: bool,
pub pushable: bool,
pub hits_pushable: bool,
pub carry: PistonCarry,
pub resectioned: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EntityFacts {
pub step_height: f32,
pub ignored: bool,
pub pushable: bool,
pub collidable: bool,
pub attached: bool,
pub living: bool,
}
#[must_use]
pub fn entity_facts(name: &str) -> Option<EntityFacts> {
let i = ENTITIES.binary_search_by(|e| e.0.cmp(name)).ok()?;
let (_, step_height, b) = ENTITIES[i];
Some(EntityFacts {
step_height,
ignored: b & 1 != 0,
pushable: b & 2 != 0,
collidable: b & 4 != 0,
attached: b & 8 != 0,
living: b & 16 != 0,
})
}
fn section_of(p: [f64; 3]) -> [i32; 3] {
let f = |v: f64| crate::math::floor(v) >> 4;
[f(p[0]), f(p[1]), f(p[2])]
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlayerPlace {
pub rank: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PistonCarry {
delta: [f64; 3],
delta_time: i64,
}
struct Actors<'a, 'b, 'c> {
p: Option<PlayerRef<'a, 'b>>,
others: &'c mut [PistonEntity],
player_rank: usize,
}
#[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 = if self.p.is_some() {
Some(self.player_rank.min(n))
} else {
None
};
(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 pos(&self, a: Actor) -> [f64; 3] {
match a {
Actor::Player => self.p.as_ref().expect("player").0.pos,
Actor::Other(k) => self.others[k].pos,
}
}
}
impl Pistons {
#[allow(clippy::too_many_arguments)]
pub fn tick_after_entities_among<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
others: &mut [PistonEntity],
player: PlayerPlace,
world: &W,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
let level = p.level;
let mut a = Actors {
p: Some((p, x, around)),
others,
player_rank: player.rank,
};
tick_moving(&mut a, world, &level, time, self, edits);
}
}
}
type PlayerRef<'a, 'b> = (&'a mut PlayerState, &'a mut PlayerExt, &'a Surroundings<'b>);
fn tick_moving<W: BlockView<State = BlockState>>(
actors: &mut Actors<'_, '_, '_>,
world: &W,
level: &LevelInfo,
time: i64,
pistons: &mut Pistons,
edits: &mut Edits,
) {
let border = world.world_border();
let start = edits.len();
pistons.slots.retain(Option::is_some);
let mut i = 0;
while i < pistons.slots.len() {
let Some(b) = pistons.slots[i] else {
i += 1;
continue;
};
i += 1;
let here = Layered {
w: world,
edits: &edits[start..],
};
if !border.contains_block(b.pos[0], b.pos[2])
|| b.pos[1] < level.min_y
|| b.pos[1] >= level.min_y + level.height
|| here.block(b.pos[0], b.pos[1], b.pos[2]).block() != Block::MOVING_PISTON
{
continue;
}
let Some(m) = pistons.slots[i - 1].as_mut() else {
continue;
};
m.last_progress = m.progress;
if m.last_progress >= 1.0 {
if m.hold < CLIENT_HOLD {
m.hold += 1;
continue;
}
let m = *m;
pistons.slots[i - 1] = None;
let mut ov = Overlay {
w: world,
level: *level,
edits,
start,
pistons,
};
if ov.get(m.pos).block() == Block::MOVING_PISTON {
let s = ov.neighbour_shapes(m.pushed, m.pos);
if s.is_air() {
ov.set(m.pos, m.pushed, 340, MAX_DEPTH);
} else {
let s = if s.get(Property::Waterlogged) == Some("true") {
with(s, Property::Waterlogged, "false")
} else {
s
};
ov.set(m.pos, s, 67, MAX_DEPTH);
}
}
} else {
let f = m.progress + 0.5;
let m = *m;
if actors.p.is_some() || !actors.others.is_empty() {
let view = Layered {
w: world,
edits: &edits[start..],
};
let mut cx = PushCx {
a: actors,
world: &view,
level: *level,
time,
pistons,
};
cx.push(&m, f);
cx.honey(&m, f);
}
if let Some(m) = pistons.slots[i - 1].as_mut() {
m.progress = f;
if m.progress >= 1.0 {
m.progress = 1.0;
}
}
}
}
}
struct PushCx<'a, 'b, 'c, 'd, W> {
a: &'a mut Actors<'b, 'c, 'd>,
world: &'a W,
level: LevelInfo,
time: i64,
pistons: &'a mut Pistons,
}
impl<W: BlockView<State = BlockState>> PushCx<'_, '_, '_, '_, W> {
fn found(&self, a: Actor, q: &Aabb) -> bool {
let movable = match a {
Actor::Player => !self.a.p.as_ref().expect("player").0.spectator,
Actor::Other(k) => self.a.others[k].moved,
};
movable && search_finds(self.a.pos(a), q) && self.a.bb(a).intersects(q)
}
fn push(&mut self, m: &MovingBlock, f: f32) {
let dir = m.moves();
let d = f64::from(f - m.progress);
let Some(boxes) = local_boxes(m.head_state(), m.pos) else {
return;
};
let bx = m.place(&hull(&boxes));
let query = union(&stretch(&bx, dir, d), &bx);
let list: Vec<Actor> = self.a.order().filter(|&a| self.found(a, &query)).collect();
let slime = m.pushed.block() == Block::SLIME_BLOCK;
for a in list {
if slime && a == Actor::Player {
let k = axis_index(dir);
self.a.p.as_mut().expect("player").0.vel[k] = f64::from(offset(dir)[k]);
}
let mut h: f64 = 0.0;
for b in &boxes {
let b3 = stretch(&m.place(b), dir, d);
let bb = self.a.bb(a);
if b3.intersects(&bb) {
h = h.max(reach(&b3, dir, &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(a, dir, dir, h);
if !m.extending && m.source {
self.pull_back(a, m, dir, d);
}
}
}
}
fn pull_back(&mut self, a: Actor, m: &MovingBlock, dir: Facing, amount: f64) {
let bb = self.a.bb(a);
let cell = Aabb::new(
f64::from(m.pos[0]),
f64::from(m.pos[1]),
f64::from(m.pos[2]),
f64::from(m.pos[0]) + 1.0,
f64::from(m.pos[1]) + 1.0,
f64::from(m.pos[2]) + 1.0,
);
if !bb.intersects(&cell) {
return;
}
let back = opposite(dir);
let d = reach(&cell, back, &bb) + 0.01;
let e = reach(&cell, back, &intersect(&bb, &cell)) + 0.01;
if (d - e).abs() < 0.01 {
let d = d.min(amount) + 0.01;
self.move_by_piston(a, 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 = local_boxes(m.pushed, m.pos).map_or(f64::NEG_INFINITY, |b| {
b.iter().map(|b| b.max_y).fold(f64::NEG_INFINITY, f64::max)
});
let bx = m.place(&Aabb::new(0.0, top, 0.0, 1.0, 1.500_001_000_000_000_1, 1.0));
let e = f64::from(f - m.progress);
let stands = |bb: &Aabb, pos: [f64; 3], on_ground: bool, supported: Option<[i32; 3]>| {
on_ground
&& bb.intersects(&bx)
&& (supported == Some(m.pos)
|| (pos[0] >= bx.min_x
&& pos[0] <= bx.max_x
&& pos[2] >= bx.min_z
&& pos[2] <= bx.max_z))
};
let list: Vec<Actor> = self
.a
.order()
.filter(|&a| {
search_finds(self.a.pos(a), &bx)
&& match a {
Actor::Player => {
let p = &*self.a.p.as_ref().expect("player").0;
stands(&p.bb, p.pos, p.on_ground, p.supporting_block)
}
Actor::Other(k) => {
let o = &self.a.others[k];
o.normal && stands(&o.bb, o.pos, o.on_ground, o.supported_by)
}
}
})
.collect();
for a in list {
self.move_by_piston(a, dir, dir, e);
}
}
fn move_by_piston(&mut self, a: Actor, pushing: Facing, dir: 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 a {
Actor::Player => self.move_player(pushing, d),
Actor::Other(k) => self.move_other(k, pushing, d),
}
}
fn colliders(&self, mover: Actor, q: &Aabb) -> Vec<Aabb> {
let hits_pushable = match mover {
Actor::Player => false,
Actor::Other(k) => self.a.others[k].hits_pushable,
};
let q = q.grow(1.0e-7, 1.0e-7, 1.0e-7);
self.a
.order()
.filter(|&b| {
b != mover && search_finds(self.a.pos(b), &q) && self.a.bb(b).intersects(&q)
})
.filter(|&b| match b {
Actor::Player => {
let p = &*self.a.p.as_ref().expect("player").0;
hits_pushable && !p.spectator && !self.player_climbing()
}
Actor::Other(j) => {
let t = &self.a.others[j];
t.collidable || (hits_pushable && t.pushable)
}
})
.map(|b| self.a.bb(b))
.collect()
}
fn player_climbing(&self) -> bool {
let p = &*self.a.p.as_ref().expect("player").0;
super::super::on_climbable::<R, W>(p, self.world)
}
fn move_player(&mut self, pushing: Facing, d: [f64; 3]) {
let time = self.time;
let shapes = self.pistons.shapes(Some(pushing));
let swept = {
let p = &*self.a.p.as_ref().expect("player").0;
let mv = |b: &Aabb| b.stretch(d[0], d[1], d[2]);
mv(&p.bb)
};
let others = if self.a.others.iter().any(|o| o.collidable) {
self.colliders(Actor::Player, &swept)
} else {
Vec::new()
};
let pistons = &mut *self.pistons;
let (p, x, around) = self.a.p.as_mut().expect("player");
if p.no_physics {
p.set_pos(p.pos[0] + d[0], p.pos[1] + d[1], p.pos[2] + d[2]);
p.horizontal_collision = false;
p.vertical_collision = false;
p.vertical_collision_below = false;
p.minor_horizontal_collision = false;
return;
}
let Some(d) = piston_budget(&mut pistons.delta, &mut pistons.delta_time, time, d) else {
return;
};
let before = section_of(p.pos);
if others.is_empty() {
move_player_by_piston::<R, W>(p, x, around.entities, self.world, &shapes, d);
} else {
let mut ents = around.entities.to_vec();
ents.extend(others);
move_player_by_piston::<R, W>(p, x, &ents, self.world, &shapes, d);
}
if section_of(p.pos) != before {
pistons.player_resectioned = true;
}
}
fn move_other(&mut self, k: usize, pushing: Facing, d: [f64; 3]) {
let time = self.time;
let o = self.a.others[k];
let mut carry = o.carry;
let Some(m) = piston_budget(&mut carry.delta, &mut carry.delta_time, time, d) else {
self.a.others[k].carry = carry;
return;
};
let q = o.bb.stretch(m[0], m[1], m[2]);
let ents = self.colliders(Actor::Other(k), &q);
let shapes = self.pistons.shapes(Some(pushing));
let mv = super::super::player::collide_other::<R, W>(
self.world,
&self.level,
o.pos,
&o.bb,
m,
o.on_ground,
o.step_height,
&ents,
&shapes,
);
let t = &mut self.a.others[k];
t.carry = carry;
let len = mv[0] * mv[0] + mv[1] * mv[1] + mv[2] * mv[2];
let dl = m[0] * m[0] + m[1] * m[1] + m[2] * m[2];
if len > 1.0e-7 || dl - len < 1.0e-7 {
let n = [t.pos[0] + mv[0], t.pos[1] + mv[1], t.pos[2] + mv[2]];
t.pos = if t.snaps {
let f = crate::math::floor;
[
f64::from(f(n[0])) + 0.5,
f64::from(f(n[1] + 0.5)),
f64::from(f(n[2])) + 0.5,
]
} else {
n
};
t.bb = t.local.offset(t.pos[0], t.pos[1], t.pos[2]);
if section_of(t.pos) != section_of(o.pos) {
t.resectioned = true;
}
}
if m[1].abs() > 0.0 {
t.on_ground = m[1] != mv[1] && m[1] < 0.0;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
fn golden(file: &str) -> Vec<serde_json::Value> {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden")
.join(if ver::BLOCK_COUNT == 1168 {
"26.1"
} else {
"26.2"
})
.join(file);
let mut text = String::new();
flate2::read::GzDecoder::new(std::fs::File::open(path).expect("golden"))
.read_to_string(&mut text)
.expect("gzip");
text.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect()
}
fn points(v: &serde_json::Value) -> Vec<f64> {
v.as_array()
.unwrap()
.iter()
.map(|p| p[0].as_f64().unwrap())
.collect()
}
fn dumped(part: &Part) -> ([Vec<f64>; 3], String) {
let v = super::super::part_view(part);
let pts: [Vec<f64>; 3] =
std::array::from_fn(|a| (0..=v.axes[a].cells()).map(|i| v.axes[a].get(i)).collect());
let mut filled = String::new();
for x in 0..v.axes[0].cells() {
for y in 0..v.axes[1].cells() {
for z in 0..v.axes[2].cells() {
filled.push(if v.filled(x as isize, y as isize, z as isize) {
'1'
} else {
'0'
});
}
}
}
(pts, filled)
}
#[test]
fn moving_shapes_match_oracle_dump() {
let mut n = 0;
for (file, source) in [
("moving_shapes.jsonl.gz", false),
("piston_shapes.jsonl.gz", true),
] {
for v in golden(file) {
let facing = v["facing"].as_u64().unwrap() as Facing;
let progress = v["progress"][0].as_f64().unwrap() as f32;
let (pushed, extending) = if source {
let f = FACING_NAMES[facing as usize];
match v["kind"].as_str().unwrap() {
"head" => (
with(Block::PISTON_HEAD.default_state(), Property::Facing, f),
true,
),
"base" => (
with(Block::PISTON.default_state(), Property::Facing, f),
false,
),
_ => (
with(Block::STICKY_PISTON.default_state(), Property::Facing, f),
false,
),
}
} else {
(
BlockState::from_id(v["state"].as_u64().unwrap() as u16).unwrap(),
v["extending"].as_bool().unwrap(),
)
};
let m = MovingBlock {
pos: [0, 0, 0],
pushed,
facing,
extending,
source,
progress,
last_progress: progress,
hold: 0,
};
let mut out = MovingShapes::new();
add_shape(&mut out, &m, None);
let part = out.at([0, 0, 0]).next().expect("a shape");
let (pts, filled) = dumped(part);
let want = [
points(&v["points_x"]),
points(&v["points_y"]),
points(&v["points_z"]),
];
assert_eq!(pts, want, "{v}");
assert_eq!(filled, v["filled"].as_str().unwrap(), "{v}");
n += 1;
}
}
assert!(n > 2400);
}
#[test]
fn facts_match_oracle_dump() {
let facts = golden("piston_facts.jsonl.gz");
assert_eq!(facts.len(), ver::BLOCK_COUNT);
for v in facts {
let b = Block::from_id(v["block"].as_u64().unwrap() as u16).unwrap();
assert_eq!(b.name(), v["name"].as_str().unwrap());
let r = v["piston"].as_u64().unwrap() as u8;
assert_eq!(FACTS[usize::from(b.id())] & 7, r, "{}", b.name());
assert_eq!(
unbreakable(b),
v["unbreakable"].as_bool().unwrap(),
"{}",
b.name()
);
assert_eq!(
has_block_entity(b),
v["block_entity"].as_bool().unwrap(),
"{}",
b.name()
);
assert_eq!(
update_class(b),
v["shape_update"].as_str().unwrap(),
"{}",
b.name()
);
let flag = |k: &str| v[k].as_bool().unwrap();
assert_eq!(tag(b, 1), flag("walls"), "{}", b.name());
assert_eq!(tag(b, 2), flag("fences"), "{}", b.name());
assert_eq!(tag(b, 4), flag("wooden_fences"), "{}", b.name());
assert_eq!(tag(b, 8), flag("wall_post_override"), "{}", b.name());
assert_eq!(tag(b, 16), flag("cannot_connect"), "{}", b.name());
assert_eq!(tag(b, 32), flag("snow"), "{}", b.name());
}
}
}