Mappings updated to official.

This commit is contained in:
stfwi 2021-07-16 09:48:58 +02:00
parent cc23672eba
commit 011edac67f
75 changed files with 21383 additions and 21336 deletions

View file

@ -26,7 +26,8 @@ repositories {
} }
minecraft { minecraft {
mappings channel: 'snapshot', version: "${version_fml_mappings}" // mappings channel: 'snapshot', version: "${version_fml_mappings}"
mappings channel: "official", version: "1.16.5"
// accessTransformer = file('build/resources/main/META-INF/accesstransformer.cfg') // accessTransformer = file('build/resources/main/META-INF/accesstransformer.cfg')
runs { runs {
client { client {

View file

@ -5,4 +5,4 @@ version_minecraft=1.16.4
version_forge_minecraft=1.16.4-35.1.10 version_forge_minecraft=1.16.4-35.1.10
version_fml_mappings=20201028-1.16.3 version_fml_mappings=20201028-1.16.3
version_jei=1.16.4:7.6.1.63 version_jei=1.16.4:7.6.1.63
version_engineersdecor=1.1.14 version_engineersdecor=1.1.15-b1

View file

@ -11,6 +11,8 @@ Mod sources for Minecraft version 1.16.x.
## Version history ## Version history
~ v1.1.15-b1 [F]
- v1.1.14 [R] Release build v1.1.14. - v1.1.14 [R] Release build v1.1.14.
- v1.1.14-b3 [A] Spanish language support added (PR#180, thx FrannDzs). - v1.1.14-b3 [A] Spanish language support added (PR#180, thx FrannDzs).

File diff suppressed because it is too large Load diff

View file

@ -118,7 +118,7 @@ public class ModEngineersDecor
// //
public static final ItemGroup ITEMGROUP = (new ItemGroup("tab" + MODID) { public static final ItemGroup ITEMGROUP = (new ItemGroup("tab" + MODID) {
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public ItemStack createIcon() public ItemStack makeIcon()
{ return new ItemStack(ModContent.SIGN_MODLOGO); } { return new ItemStack(ModContent.SIGN_MODLOGO); }
}); });
@ -128,9 +128,9 @@ public class ModEngineersDecor
@SubscribeEvent @SubscribeEvent
public void onPlayerEvent(final LivingEvent.LivingUpdateEvent event) public void onPlayerEvent(final LivingEvent.LivingUpdateEvent event)
{ {
if((event.getEntity().world == null) || (!(event.getEntity() instanceof PlayerEntity))) return; if((event.getEntity().level == null) || (!(event.getEntity() instanceof PlayerEntity))) return;
final PlayerEntity player = (PlayerEntity)event.getEntity(); final PlayerEntity player = (PlayerEntity)event.getEntity();
if(player.isOnLadder()) EdLadderBlock.onPlayerUpdateEvent(player); if(player.onClimbable()) EdLadderBlock.onPlayerUpdateEvent(player);
} }
} }

View file

@ -12,17 +12,18 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.AbstractBlock;
import wile.engineersdecor.libmc.blocks.StandardBlocks; import wile.engineersdecor.libmc.blocks.StandardBlocks;
import wile.engineersdecor.libmc.blocks.StandardBlocks.IStandardBlock; import wile.engineersdecor.libmc.blocks.StandardBlocks.IStandardBlock;
import wile.engineersdecor.libmc.detail.Auxiliaries; import wile.engineersdecor.libmc.detail.Auxiliaries;
import net.minecraft.block.IWaterLoggable; import net.minecraft.block.IWaterLoggable;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.block.Block;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.function.Supplier; import java.util.function.Supplier;
public class DecorBlock public class DecorBlock
{ {
public static final long CFG_DEFAULT = StandardBlocks.CFG_DEFAULT; public static final long CFG_DEFAULT = StandardBlocks.CFG_DEFAULT;
@ -43,91 +44,91 @@ public class DecorBlock
public static class Normal extends StandardBlocks.BaseBlock implements IDecorBlock public static class Normal extends StandardBlocks.BaseBlock implements IDecorBlock
{ {
public Normal(long conf, Block.Properties properties) public Normal(long conf, AbstractBlock.Properties properties)
{ super(conf, properties); } { super(conf, properties); }
} }
public static class Cutout extends StandardBlocks.Cutout implements IDecorBlock public static class Cutout extends StandardBlocks.Cutout implements IDecorBlock
{ {
public Cutout(long conf, Block.Properties properties) public Cutout(long conf, AbstractBlock.Properties properties)
{ super(conf, properties, Auxiliaries.getPixeledAABB(0, 0, 0, 16, 16,16 )); } { super(conf, properties, Auxiliaries.getPixeledAABB(0, 0, 0, 16, 16,16 )); }
public Cutout(long conf, Block.Properties properties, AxisAlignedBB aabb) public Cutout(long conf, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ super(conf, properties, aabb);} { super(conf, properties, aabb);}
public Cutout(long conf, Block.Properties properties, VoxelShape voxel_shape) public Cutout(long conf, AbstractBlock.Properties properties, VoxelShape voxel_shape)
{ super(conf, properties, voxel_shape); } { super(conf, properties, voxel_shape); }
public Cutout(long conf, Block.Properties properties, AxisAlignedBB[] aabbs) public Cutout(long conf, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ super(conf, properties, aabbs); } { super(conf, properties, aabbs); }
} }
public static class WaterLoggable extends StandardBlocks.WaterLoggable implements IStandardBlock, IWaterLoggable public static class WaterLoggable extends StandardBlocks.WaterLoggable implements IStandardBlock, IWaterLoggable
{ {
public WaterLoggable(long config, Block.Properties properties) public WaterLoggable(long config, AbstractBlock.Properties properties)
{ super(config, properties); } { super(config, properties); }
public WaterLoggable(long config, Block.Properties properties, AxisAlignedBB aabb) public WaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ super(config, properties, aabb); } { super(config, properties, aabb); }
public WaterLoggable(long config, Block.Properties properties, AxisAlignedBB[] aabbs) public WaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ super(config, properties, aabbs); } { super(config, properties, aabbs); }
public WaterLoggable(long config, Block.Properties properties, VoxelShape voxel_shape) public WaterLoggable(long config, AbstractBlock.Properties properties, VoxelShape voxel_shape)
{ super(config, properties, voxel_shape); } { super(config, properties, voxel_shape); }
} }
public static class Directed extends StandardBlocks.Directed implements IDecorBlock public static class Directed extends StandardBlocks.Directed implements IDecorBlock
{ {
public Directed(long config, Block.Properties properties, final AxisAlignedBB unrotatedAABB) public Directed(long config, AbstractBlock.Properties properties, final AxisAlignedBB unrotatedAABB)
{ super(config, properties, unrotatedAABB); } { super(config, properties, unrotatedAABB); }
public Directed(long config, Block.Properties properties, final AxisAlignedBB[] unrotatedAABBs) public Directed(long config, AbstractBlock.Properties properties, final AxisAlignedBB[] unrotatedAABBs)
{ super(config, properties, unrotatedAABBs); } { super(config, properties, unrotatedAABBs); }
public Directed(long config, Block.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier) public Directed(long config, AbstractBlock.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ super(config, properties, shape_supplier); } { super(config, properties, shape_supplier); }
} }
public static class DirectedWaterLoggable extends StandardBlocks.DirectedWaterLoggable implements IDecorBlock,IWaterLoggable public static class DirectedWaterLoggable extends StandardBlocks.DirectedWaterLoggable implements IDecorBlock,IWaterLoggable
{ {
public DirectedWaterLoggable(long config, Block.Properties properties, AxisAlignedBB aabb) public DirectedWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ super(config, properties, aabb); } { super(config, properties, aabb); }
public DirectedWaterLoggable(long config, Block.Properties properties, AxisAlignedBB[] aabbs) public DirectedWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ super(config, properties, aabbs); } { super(config, properties, aabbs); }
public DirectedWaterLoggable(long config, Block.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier) public DirectedWaterLoggable(long config, AbstractBlock.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ super(config, properties, shape_supplier); } { super(config, properties, shape_supplier); }
} }
public static class Horizontal extends StandardBlocks.Horizontal implements IDecorBlock public static class Horizontal extends StandardBlocks.Horizontal implements IDecorBlock
{ {
public Horizontal(long config, Block.Properties properties, final AxisAlignedBB unrotatedAABB) public Horizontal(long config, AbstractBlock.Properties properties, final AxisAlignedBB unrotatedAABB)
{ super(config, properties, unrotatedAABB); } { super(config, properties, unrotatedAABB); }
public Horizontal(long config, Block.Properties properties, final AxisAlignedBB[] unrotatedAABBs) public Horizontal(long config, AbstractBlock.Properties properties, final AxisAlignedBB[] unrotatedAABBs)
{ super(config, properties, unrotatedAABBs); } { super(config, properties, unrotatedAABBs); }
public Horizontal(long config, Block.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier) public Horizontal(long config, AbstractBlock.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ super(config, properties, shape_supplier); } { super(config, properties, shape_supplier); }
} }
public static class HorizontalWaterLoggable extends StandardBlocks.HorizontalWaterLoggable implements IWaterLoggable public static class HorizontalWaterLoggable extends StandardBlocks.HorizontalWaterLoggable implements IWaterLoggable
{ {
public HorizontalWaterLoggable(long config, Block.Properties properties, AxisAlignedBB aabb) public HorizontalWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ super(config, properties, aabb); } { super(config, properties, aabb); }
public HorizontalWaterLoggable(long config, Block.Properties properties, AxisAlignedBB[] aabbs) public HorizontalWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ super(config, properties, aabbs); } { super(config, properties, aabbs); }
public HorizontalWaterLoggable(long config, Block.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier) public HorizontalWaterLoggable(long config, AbstractBlock.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ super(config, properties, shape_supplier); } { super(config, properties, shape_supplier); }
} }
public static class HorizontalFourWayWaterLoggable extends StandardBlocks.HorizontalFourWayWaterLoggable implements IWaterLoggable public static class HorizontalFourWayWaterLoggable extends StandardBlocks.HorizontalFourWayWaterLoggable implements IWaterLoggable
{ {
public HorizontalFourWayWaterLoggable(long config, Block.Properties properties, AxisAlignedBB base_aabb, AxisAlignedBB side_aabb, int railing_height_extension) public HorizontalFourWayWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB base_aabb, AxisAlignedBB side_aabb, int railing_height_extension)
{ super(config, properties, base_aabb, side_aabb, railing_height_extension); } { super(config, properties, base_aabb, side_aabb, railing_height_extension); }
} }

View file

@ -19,6 +19,7 @@ import net.minecraft.world.GameRules;
import net.minecraft.world.server.ServerWorld; import net.minecraft.world.server.ServerWorld;
import net.minecraft.state.BooleanProperty; import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer; import net.minecraft.state.StateContainer;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.block.SoundType; import net.minecraft.block.SoundType;
import net.minecraft.block.Block; import net.minecraft.block.Block;
@ -50,6 +51,7 @@ import java.util.List;
import java.util.Random; import java.util.Random;
public class EdBreaker public class EdBreaker
{ {
public static void on_config(int boost_energy_per_tick, int breaking_time_per_hardness, int min_breaking_time_ticks, boolean power_required) public static void on_config(int boost_energy_per_tick, int breaking_time_per_hardness, int min_breaking_time_ticks, boolean power_required)
@ -63,17 +65,17 @@ public class EdBreaker
{ {
public static final BooleanProperty ACTIVE = BooleanProperty.create("active"); public static final BooleanProperty ACTIVE = BooleanProperty.create("active");
public BreakerBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABBs) public BreakerBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABBs)
{ super(config, builder, unrotatedAABBs); } { super(config, builder, unrotatedAABBs); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(ACTIVE); } { super.createBlockStateDefinition(builder); builder.add(ACTIVE); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(ACTIVE, false); } { return super.getStateForPlacement(context).setValue(ACTIVE, false); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -87,12 +89,12 @@ public class EdBreaker
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void animateTick(BlockState state, World world, BlockPos pos, Random rnd) public void animateTick(BlockState state, World world, BlockPos pos, Random rnd)
{ {
if((state.getBlock()!=this) || (!state.get(ACTIVE))) return; if((state.getBlock()!=this) || (!state.getValue(ACTIVE))) return;
final double rv = rnd.nextDouble(); final double rv = rnd.nextDouble();
if(rv > 0.8) return; if(rv > 0.8) return;
final double x=0.5+pos.getX(), y=0.5+pos.getY(), z=0.5+pos.getZ(); final double x=0.5+pos.getX(), y=0.5+pos.getY(), z=0.5+pos.getZ();
final double xc=0.52, xr=rnd.nextDouble()*0.4-0.2, yr=(y-0.3+rnd.nextDouble()*0.2); final double xc=0.52, xr=rnd.nextDouble()*0.4-0.2, yr=(y-0.3+rnd.nextDouble()*0.2);
switch(state.get(HORIZONTAL_FACING)) { switch(state.getValue(HORIZONTAL_FACING)) {
case WEST: world.addParticle(ParticleTypes.SMOKE, x-xc, yr, z+xr, 0.0, 0.0, 0.0); break; case WEST: world.addParticle(ParticleTypes.SMOKE, x-xc, yr, z+xr, 0.0, 0.0, 0.0); break;
case EAST: world.addParticle(ParticleTypes.SMOKE, x+xc, yr, z+xr, 0.0, 0.0, 0.0); break; case EAST: world.addParticle(ParticleTypes.SMOKE, x+xc, yr, z+xr, 0.0, 0.0, 0.0); break;
case NORTH: world.addParticle(ParticleTypes.SMOKE, x+xr, yr, z-xc, 0.0, 0.0, 0.0); break; case NORTH: world.addParticle(ParticleTypes.SMOKE, x+xr, yr, z-xc, 0.0, 0.0, 0.0); break;
@ -104,33 +106,33 @@ public class EdBreaker
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused)
{ {
if(!(world instanceof World) || (((World) world).isRemote)) return; if(!(world instanceof World) || (((World) world).isClientSide)) return;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof BreakerTileEntity)) return; if(!(te instanceof BreakerTileEntity)) return;
((BreakerTileEntity)te).block_updated(); ((BreakerTileEntity)te).block_updated();
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean canProvidePower(BlockState state) public boolean isSignalSource(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getWeakPower(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side) public int getSignal(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side)
{ return 0; } { return 0; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getStrongPower(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side) public int getDirectSignal(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side)
{ return 0; } { return 0; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(te instanceof BreakerTileEntity) ((BreakerTileEntity)te).state_message(player); if(te instanceof BreakerTileEntity) ((BreakerTileEntity)te).state_message(player);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@ -202,17 +204,17 @@ public class EdBreaker
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt); return nbt; } { super.save(nbt); writenbt(nbt); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
energy_handler_.invalidate(); energy_handler_.invalidate();
} }
@ -227,7 +229,7 @@ public class EdBreaker
// ITickable ------------------------------------------------------------------------------------ // ITickable ------------------------------------------------------------------------------------
private static HashSet<Block> blacklist = new HashSet<>(); private static final HashSet<Block> blacklist = new HashSet<>();
static { static {
blacklist.add(Blocks.AIR); blacklist.add(Blocks.AIR);
blacklist.add(Blocks.BEDROCK); blacklist.add(Blocks.BEDROCK);
@ -245,22 +247,22 @@ public class EdBreaker
if(blacklist.contains(block)) return false; if(blacklist.contains(block)) return false;
if(state.getMaterial().isLiquid()) return false; if(state.getMaterial().isLiquid()) return false;
if(block.isAir(state, world, pos)) return false; if(block.isAir(state, world, pos)) return false;
float bh = state.getBlockHardness(world, pos); float bh = state.getDestroySpeed(world, pos);
if((bh<0) || (bh>55)) return false; if((bh<0) || (bh>55)) return false;
return true; return true;
} }
private static void spawnBlockAsEntity(World world, BlockPos pos, ItemStack stack) { private static void spawnBlockAsEntity(World world, BlockPos pos, ItemStack stack) {
if(world.isRemote || stack.isEmpty() || (!world.getGameRules().getBoolean(GameRules.DO_TILE_DROPS)) || world.restoringBlockSnapshots) return; if(world.isClientSide || stack.isEmpty() || (!world.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS)) || world.restoringBlockSnapshots) return;
ItemEntity e = new ItemEntity(world, ItemEntity e = new ItemEntity(world,
((world.rand.nextFloat()*0.1)+0.5) + pos.getX(), ((world.random.nextFloat()*0.1)+0.5) + pos.getX(),
((world.rand.nextFloat()*0.1)+0.5) + pos.getY(), ((world.random.nextFloat()*0.1)+0.5) + pos.getY(),
((world.rand.nextFloat()*0.1)+0.5) + pos.getZ(), ((world.random.nextFloat()*0.1)+0.5) + pos.getZ(),
stack stack
); );
e.setDefaultPickupDelay(); e.setDefaultPickUpDelay();
e.setMotion((world.rand.nextFloat()*0.1-0.05), (world.rand.nextFloat()*0.1-0.03), (world.rand.nextFloat()*0.1-0.05)); e.setDeltaMovement((world.random.nextFloat()*0.1-0.05), (world.random.nextFloat()*0.1-0.03), (world.random.nextFloat()*0.1-0.05));
world.addEntity(e); world.addFreshEntity(e);
} }
private static boolean canInsertInto(World world, BlockPos pos) private static boolean canInsertInto(World world, BlockPos pos)
@ -273,17 +275,17 @@ public class EdBreaker
private boolean breakBlock(BlockState state, BlockPos pos, World world) private boolean breakBlock(BlockState state, BlockPos pos, World world)
{ {
if(world.isRemote || (!(world instanceof ServerWorld)) || world.restoringBlockSnapshots) return false; // retry next cycle if(world.isClientSide || (!(world instanceof ServerWorld)) || world.restoringBlockSnapshots) return false; // retry next cycle
List<ItemStack> drops; List<ItemStack> drops;
final Block block = state.getBlock(); final Block block = state.getBlock();
final boolean insert = canInsertInto(world, getPos().down()); final boolean insert = canInsertInto(world, getBlockPos().below());
drops = Block.getDrops(state, (ServerWorld)world, pos, world.getTileEntity(pos)); drops = Block.getDrops(state, (ServerWorld)world, pos, world.getBlockEntity(pos));
world.removeBlock(pos, false); world.removeBlock(pos, false);
for(ItemStack drop:drops) { for(ItemStack drop:drops) {
if(!insert) { if(!insert) {
spawnBlockAsEntity(world, pos, drop); spawnBlockAsEntity(world, pos, drop);
} else { } else {
final ItemStack remaining = Inventories.insert(world, getPos().down(), Direction.UP, drop, false); final ItemStack remaining = Inventories.insert(world, getBlockPos().below(), Direction.UP, drop, false);
if(!remaining.isEmpty()) spawnBlockAsEntity(world, pos, remaining); if(!remaining.isEmpty()) spawnBlockAsEntity(world, pos, remaining);
} }
} }
@ -297,35 +299,35 @@ public class EdBreaker
public void tick() public void tick()
{ {
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
final BlockState device_state = world.getBlockState(pos); final BlockState device_state = level.getBlockState(worldPosition);
if(!(device_state.getBlock() instanceof BreakerBlock)) return; if(!(device_state.getBlock() instanceof BreakerBlock)) return;
if(world.isRemote) { if(level.isClientSide) {
if(!device_state.get(BreakerBlock.ACTIVE)) { if(!device_state.getValue(BreakerBlock.ACTIVE)) {
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
} else { } else {
tick_timer_ = 1; tick_timer_ = 1;
// not sure if is so cool to do this each tick ... may be simplified/removed again. // not sure if is so cool to do this each tick ... may be simplified/removed again.
SoundEvent sound = SoundEvents.BLOCK_WOOD_HIT; SoundEvent sound = SoundEvents.WOOD_HIT;
BlockState target_state = world.getBlockState(pos.offset(device_state.get(BreakerBlock.HORIZONTAL_FACING))); BlockState target_state = level.getBlockState(worldPosition.relative(device_state.getValue(BreakerBlock.HORIZONTAL_FACING)));
SoundType stype = target_state.getBlock().getSoundType(target_state); SoundType stype = target_state.getBlock().getSoundType(target_state);
if((stype == SoundType.CLOTH) || (stype == SoundType.PLANT) || (stype == SoundType.SNOW)) { if((stype == SoundType.WOOL) || (stype == SoundType.GRASS) || (stype == SoundType.SNOW)) {
sound = SoundEvents.BLOCK_WOOL_HIT; sound = SoundEvents.WOOL_HIT;
} else if((stype == SoundType.GROUND) || (stype == SoundType.SAND)) { } else if((stype == SoundType.GRAVEL) || (stype == SoundType.SAND)) {
sound = SoundEvents.BLOCK_GRAVEL_HIT; sound = SoundEvents.GRAVEL_HIT;
} }
world.playSound(pos.getX(), pos.getY(), pos.getZ(), sound, SoundCategory.BLOCKS, 0.1f, 1.2f, false); level.playLocalSound(worldPosition.getX(), worldPosition.getY(), worldPosition.getZ(), sound, SoundCategory.BLOCKS, 0.1f, 1.2f, false);
} }
} else { } else {
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
final BlockPos target_pos = pos.offset(device_state.get(BreakerBlock.HORIZONTAL_FACING)); final BlockPos target_pos = worldPosition.relative(device_state.getValue(BreakerBlock.HORIZONTAL_FACING));
final BlockState target_state = world.getBlockState(target_pos); final BlockState target_state = level.getBlockState(target_pos);
if((world.isBlockPowered(pos)) || (!isBreakable(target_state, target_pos, world))) { if((level.hasNeighborSignal(worldPosition)) || (!isBreakable(target_state, target_pos, level))) {
if(device_state.get(BreakerBlock.ACTIVE)) world.setBlockState(pos, device_state.with(BreakerBlock.ACTIVE, false), 1|2); if(device_state.getValue(BreakerBlock.ACTIVE)) level.setBlock(worldPosition, device_state.setValue(BreakerBlock.ACTIVE, false), 1|2);
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
tick_timer_ = IDLE_TICK_INTERVAL; tick_timer_ = IDLE_TICK_INTERVAL;
return; return;
} }
time_needed_ = MathHelper.clamp((int)(target_state.getBlockHardness(world, pos) * breaking_reluctance) + min_breaking_time, min_breaking_time, MAX_BREAKING_TIME); time_needed_ = MathHelper.clamp((int)(target_state.getDestroySpeed(level, worldPosition) * breaking_reluctance) + min_breaking_time, min_breaking_time, MAX_BREAKING_TIME);
if(battery_.draw(boost_energy_consumption)) { if(battery_.draw(boost_energy_consumption)) {
proc_time_elapsed_ += TICK_INTERVAL * (1+BOOST_FACTOR); proc_time_elapsed_ += TICK_INTERVAL * (1+BOOST_FACTOR);
time_needed_ += min_breaking_time * (3*BOOST_FACTOR/5); time_needed_ += min_breaking_time * (3*BOOST_FACTOR/5);
@ -342,11 +344,11 @@ public class EdBreaker
} }
if(proc_time_elapsed_ >= time_needed_) { if(proc_time_elapsed_ >= time_needed_) {
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
breakBlock(target_state, target_pos, world); breakBlock(target_state, target_pos, level);
active = false; active = false;
} }
if(device_state.get(BreakerBlock.ACTIVE) != active) { if(device_state.getValue(BreakerBlock.ACTIVE) != active) {
world.setBlockState(pos, device_state.with(BreakerBlock.ACTIVE, active), 1|2); level.setBlock(worldPosition, device_state.setValue(BreakerBlock.ACTIVE, active), 1|2);
} }
} }
} }

View file

@ -8,6 +8,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
@ -32,12 +33,13 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class EdCatwalkBlock extends DecorBlock.HorizontalFourWayWaterLoggable implements IDecorBlock public class EdCatwalkBlock extends DecorBlock.HorizontalFourWayWaterLoggable implements IDecorBlock
{ {
final Block railing_block; final Block railing_block;
final AxisAlignedBB base_aabb; final AxisAlignedBB base_aabb;
public EdCatwalkBlock(long config, Block.Properties properties, final AxisAlignedBB base_aabb, final AxisAlignedBB railing_aabb, final Block railing_block) public EdCatwalkBlock(long config, AbstractBlock.Properties properties, final AxisAlignedBB base_aabb, final AxisAlignedBB railing_aabb, final Block railing_block)
{ super(config, properties, base_aabb, railing_aabb, 0); this.railing_block = railing_block; this.base_aabb=base_aabb; } { super(config, properties, base_aabb, railing_aabb, 0); this.railing_block = railing_block; this.base_aabb=base_aabb; }
@Override @Override
@ -47,14 +49,14 @@ public class EdCatwalkBlock extends DecorBlock.HorizontalFourWayWaterLoggable im
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(NORTH, false).with(EAST, false).with(SOUTH, false).with(WEST, false); } { return super.getStateForPlacement(context).setValue(NORTH, false).setValue(EAST, false).setValue(SOUTH, false).setValue(WEST, false); }
public static boolean place_consume(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, int shrink) public static boolean place_consume(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, int shrink)
{ {
if(!world.setBlockState(pos, state, 1|2)) return false; if(!world.setBlock(pos, state, 1|2)) return false;
world.playSound(player, pos, SoundEvents.BLOCK_METAL_PLACE, SoundCategory.BLOCKS, 1f, 1f); world.playSound(player, pos, SoundEvents.METAL_PLACE, SoundCategory.BLOCKS, 1f, 1f);
if((!player.isCreative()) && (!world.isRemote())) { if((!player.isCreative()) && (!world.isClientSide())) {
ItemStack stack = player.getHeldItem(hand); ItemStack stack = player.getItemInHand(hand);
if(shrink >= 0) { if(shrink >= 0) {
stack.shrink(shrink); stack.shrink(shrink);
} else if(stack.getCount() < stack.getMaxStackSize()) { } else if(stack.getCount() < stack.getMaxStackSize()) {
@ -69,42 +71,42 @@ public class EdCatwalkBlock extends DecorBlock.HorizontalFourWayWaterLoggable im
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
final Item item = player.getHeldItem(hand).getItem(); final Item item = player.getItemInHand(hand).getItem();
if((!(item instanceof BlockItem))) return ActionResultType.PASS; if((!(item instanceof BlockItem))) return ActionResultType.PASS;
final Block block = ((BlockItem)item).getBlock(); final Block block = ((BlockItem)item).getBlock();
if(block == this) { if(block == this) {
if(hit.getFace().getAxis().isHorizontal()) return ActionResultType.PASS; // place new block on the clicked side. if(hit.getDirection().getAxis().isHorizontal()) return ActionResultType.PASS; // place new block on the clicked side.
BlockPos adjacent_pos = pos.offset(player.getHorizontalFacing()); BlockPos adjacent_pos = pos.relative(player.getDirection());
BlockState adjacent_state = world.getBlockState(adjacent_pos); BlockState adjacent_state = world.getBlockState(adjacent_pos);
if(adjacent_state.isReplaceable(new DirectionalPlaceContext(world, adjacent_pos, hit.getFace().getOpposite(), player.getHeldItem(hand), hit.getFace()))) { if(adjacent_state.canBeReplaced(new DirectionalPlaceContext(world, adjacent_pos, hit.getDirection().getOpposite(), player.getItemInHand(hand), hit.getDirection()))) {
BlockState place_state = getDefaultState(); BlockState place_state = defaultBlockState();
place_state = place_state.with(WATERLOGGED,adjacent_state.getFluidState().getFluid()==Fluids.WATER); place_state = place_state.setValue(WATERLOGGED,adjacent_state.getFluidState().getType()==Fluids.WATER);
place_consume(place_state, world, adjacent_pos, player, hand, 1); place_consume(place_state, world, adjacent_pos, player, hand, 1);
} }
return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
} }
if(block == railing_block) { if(block == railing_block) {
Direction face = hit.getFace(); Direction face = hit.getDirection();
final Vector3d rhv = hit.getHitVec().subtract(Vector3d.copyCentered(hit.getPos())); final Vector3d rhv = hit.getLocation().subtract(Vector3d.atCenterOf(hit.getBlockPos()));
if(face.getAxis().isHorizontal()) { if(face.getAxis().isHorizontal()) {
// Side or railing clicked // Side or railing clicked
if(rhv.mul(Vector3d.copy(face.getDirectionVec())).scale(2).lengthSquared() < 0.99) face = face.getOpposite(); // click on railing, not the outer side. if(rhv.multiply(Vector3d.atLowerCornerOf(face.getNormal())).scale(2).lengthSqr() < 0.99) face = face.getOpposite(); // click on railing, not the outer side.
} else if(player.getDistanceSq(Vector3d.copyCentered(pos)) < 3) { } else if(player.distanceToSqr(Vector3d.atCenterOf(pos)) < 3) {
// near accurate placement // near accurate placement
face = Direction.getFacingFromVector(rhv.x, 0, rhv.z); face = Direction.getNearest(rhv.x, 0, rhv.z);
} else { } else {
// far automatic placement // far automatic placement
face = Direction.getFacingFromVector(player.getLookVec().x, 0, player.getLookVec().z); face = Direction.getNearest(player.getLookAngle().x, 0, player.getLookAngle().z);
List<Direction> free_sides = Arrays.stream(Direction.values()).filter(d->d.getAxis().isHorizontal() && (world.getBlockState(pos.offset(d)).getBlock()!=this)).collect(Collectors.toList()); List<Direction> free_sides = Arrays.stream(Direction.values()).filter(d->d.getAxis().isHorizontal() && (world.getBlockState(pos.relative(d)).getBlock()!=this)).collect(Collectors.toList());
if(free_sides.isEmpty()) return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; if(free_sides.isEmpty()) return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
if(!free_sides.contains(face)) face = free_sides.get(0); if(!free_sides.contains(face)) face = free_sides.get(0);
} }
BooleanProperty railing = getDirectionProperty(face); BooleanProperty railing = getDirectionProperty(face);
boolean add = (!state.get(railing)); boolean add = (!state.getValue(railing));
place_consume(state.with(railing, add), world, pos, player, hand, add ? 1 : -1); place_consume(state.setValue(railing, add), world, pos, player, hand, add ? 1 : -1);
return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
} }
return ActionResultType.PASS; return ActionResultType.PASS;
} }
@ -118,10 +120,10 @@ public class EdCatwalkBlock extends DecorBlock.HorizontalFourWayWaterLoggable im
@Override @Override
public List<ItemStack> dropList(BlockState state, World world, @Nullable TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, @Nullable TileEntity te, boolean explosion)
{ {
if(world.isRemote()) return Collections.singletonList(ItemStack.EMPTY); if(world.isClientSide()) return Collections.singletonList(ItemStack.EMPTY);
List<ItemStack> drops = new ArrayList<>(); List<ItemStack> drops = new ArrayList<>();
drops.add(new ItemStack(state.getBlock().asItem())); drops.add(new ItemStack(state.getBlock().asItem()));
int n = (state.get(NORTH)?1:0)+(state.get(EAST)?1:0)+(state.get(SOUTH)?1:0)+(state.get(WEST)?1:0); int n = (state.getValue(NORTH)?1:0)+(state.getValue(EAST)?1:0)+(state.getValue(SOUTH)?1:0)+(state.getValue(WEST)?1:0);
if(n > 0) drops.add(new ItemStack(ModContent.STEEL_RAILING, n)); if(n > 0) drops.add(new ItemStack(ModContent.STEEL_RAILING, n));
return drops; return drops;
} }

View file

@ -8,6 +8,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
@ -35,6 +36,7 @@ import javax.annotation.Nullable;
import java.util.*; import java.util.*;
public class EdCatwalkStairsBlock extends DecorBlock.HorizontalWaterLoggable implements IDecorBlock public class EdCatwalkStairsBlock extends DecorBlock.HorizontalWaterLoggable implements IDecorBlock
{ {
public static final BooleanProperty RIGHT_RAILING = BooleanProperty.create("right_railing"); public static final BooleanProperty RIGHT_RAILING = BooleanProperty.create("right_railing");
@ -43,21 +45,21 @@ public class EdCatwalkStairsBlock extends DecorBlock.HorizontalWaterLoggable imp
protected final Map<BlockState, VoxelShape> collision_shapes; protected final Map<BlockState, VoxelShape> collision_shapes;
protected final Map<Direction, Integer> y_rotations; protected final Map<Direction, Integer> y_rotations;
public EdCatwalkStairsBlock(long config, Block.Properties properties, final AxisAlignedBB[] base_aabb, final AxisAlignedBB[] railing_aabbs) public EdCatwalkStairsBlock(long config, AbstractBlock.Properties properties, final AxisAlignedBB[] base_aabb, final AxisAlignedBB[] railing_aabbs)
{ {
super(config, properties, base_aabb); super(config, properties, base_aabb);
Map<BlockState, VoxelShape> sh = new HashMap<>(); Map<BlockState, VoxelShape> sh = new HashMap<>();
Map<BlockState, VoxelShape> csh = new HashMap<>(); Map<BlockState, VoxelShape> csh = new HashMap<>();
getStateContainer().getValidStates().forEach(state->{ getStateDefinition().getPossibleStates().forEach(state->{
Direction facing = state.get(HORIZONTAL_FACING); Direction facing = state.getValue(HORIZONTAL_FACING);
VoxelShape base_shape = Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(base_aabb, facing, true)); VoxelShape base_shape = Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(base_aabb, facing, true));
if(state.get(RIGHT_RAILING)) { if(state.getValue(RIGHT_RAILING)) {
VoxelShape right_shape = Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(Auxiliaries.getMirroredAABB(railing_aabbs, Axis.X), facing, true)); VoxelShape right_shape = Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(Auxiliaries.getMirroredAABB(railing_aabbs, Axis.X), facing, true));
base_shape = VoxelShapes.combine(base_shape, right_shape, IBooleanFunction.OR); base_shape = VoxelShapes.joinUnoptimized(base_shape, right_shape, IBooleanFunction.OR);
} }
if(state.get(LEFT_RAILING)) { if(state.getValue(LEFT_RAILING)) {
VoxelShape left_shape = Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(railing_aabbs, facing, true)); VoxelShape left_shape = Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(railing_aabbs, facing, true));
base_shape = VoxelShapes.combine(base_shape, left_shape, IBooleanFunction.OR); base_shape = VoxelShapes.joinUnoptimized(base_shape, left_shape, IBooleanFunction.OR);
} }
sh.put(state, base_shape); sh.put(state, base_shape);
csh.put(state, base_shape); csh.put(state, base_shape);
@ -71,20 +73,20 @@ public class EdCatwalkStairsBlock extends DecorBlock.HorizontalWaterLoggable imp
y_rotations.put(Direction.WEST, 3); y_rotations.put(Direction.WEST, 3);
y_rotations.put(Direction.UP, 0); y_rotations.put(Direction.UP, 0);
y_rotations.put(Direction.DOWN, 0); y_rotations.put(Direction.DOWN, 0);
setDefaultState(super.getDefaultState().with(LEFT_RAILING, false).with(RIGHT_RAILING, false)); registerDefaultState(super.defaultBlockState().setValue(LEFT_RAILING, false).setValue(RIGHT_RAILING, false));
} }
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context)
{ return shapes.getOrDefault(state, VoxelShapes.fullCube()); } { return shapes.getOrDefault(state, VoxelShapes.block()); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) public VoxelShape getCollisionShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context)
{ return collision_shapes.getOrDefault(state, VoxelShapes.fullCube()); } { return collision_shapes.getOrDefault(state, VoxelShapes.block()); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(RIGHT_RAILING, LEFT_RAILING); } { super.createBlockStateDefinition(builder); builder.add(RIGHT_RAILING, LEFT_RAILING); }
@Override @Override
public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos) public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos)
@ -97,66 +99,66 @@ public class EdCatwalkStairsBlock extends DecorBlock.HorizontalWaterLoggable imp
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
final Item item = player.getHeldItem(hand).getItem(); final Item item = player.getItemInHand(hand).getItem();
if((!(item instanceof BlockItem))) return ActionResultType.PASS; if((!(item instanceof BlockItem))) return ActionResultType.PASS;
final Block block = ((BlockItem)item).getBlock(); final Block block = ((BlockItem)item).getBlock();
final Direction facing = state.get(HORIZONTAL_FACING); final Direction facing = state.getValue(HORIZONTAL_FACING);
if(block == this) { if(block == this) {
final Direction hlv = Arrays.stream(Direction.getFacingDirections(player)).filter(d->d.getAxis().isHorizontal()).findFirst().orElse(Direction.NORTH); final Direction hlv = Arrays.stream(Direction.orderedByNearest(player)).filter(d->d.getAxis().isHorizontal()).findFirst().orElse(Direction.NORTH);
BlockPos adjacent_pos; BlockPos adjacent_pos;
if(hlv == facing) { if(hlv == facing) {
adjacent_pos = pos.up().offset(hlv); adjacent_pos = pos.above().relative(hlv);
} else if(hlv == facing.getOpposite()) { } else if(hlv == facing.getOpposite()) {
adjacent_pos = pos.down().offset(hlv); adjacent_pos = pos.below().relative(hlv);
} else { } else {
return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
} }
final BlockState adjacent_state = world.getBlockState(adjacent_pos); final BlockState adjacent_state = world.getBlockState(adjacent_pos);
if(adjacent_state == null) return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; if(adjacent_state == null) return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
if(!adjacent_state.isReplaceable(new DirectionalPlaceContext(world, adjacent_pos, hit.getFace().getOpposite(), player.getHeldItem(hand), hit.getFace()))) return ActionResultType.CONSUME; if(!adjacent_state.canBeReplaced(new DirectionalPlaceContext(world, adjacent_pos, hit.getDirection().getOpposite(), player.getItemInHand(hand), hit.getDirection()))) return ActionResultType.CONSUME;
BlockState place_state = getDefaultState().with(HORIZONTAL_FACING, facing); BlockState place_state = defaultBlockState().setValue(HORIZONTAL_FACING, facing);
place_state = place_state.with(WATERLOGGED,adjacent_state.getFluidState().getFluid()==Fluids.WATER); place_state = place_state.setValue(WATERLOGGED,adjacent_state.getFluidState().getType()==Fluids.WATER);
EdCatwalkBlock.place_consume(place_state, world, adjacent_pos, player, hand, 1); EdCatwalkBlock.place_consume(place_state, world, adjacent_pos, player, hand, 1);
return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
} else if((block == ModContent.STEEL_CATWALK) || (block == ModContent.STEEL_CATWALK_TOP_ALIGNED)) { } else if((block == ModContent.STEEL_CATWALK) || (block == ModContent.STEEL_CATWALK_TOP_ALIGNED)) {
BlockPos adjacent_pos; BlockPos adjacent_pos;
adjacent_pos = pos.offset(facing); adjacent_pos = pos.relative(facing);
final BlockState adjacent_state = world.getBlockState(adjacent_pos); final BlockState adjacent_state = world.getBlockState(adjacent_pos);
if(adjacent_state == null) return ActionResultType.CONSUME; if(adjacent_state == null) return ActionResultType.CONSUME;
if(!adjacent_state.isReplaceable(new DirectionalPlaceContext(world, adjacent_pos, hit.getFace().getOpposite(), player.getHeldItem(hand), hit.getFace()))) return ActionResultType.CONSUME; if(!adjacent_state.canBeReplaced(new DirectionalPlaceContext(world, adjacent_pos, hit.getDirection().getOpposite(), player.getItemInHand(hand), hit.getDirection()))) return ActionResultType.CONSUME;
BlockState place_state = ModContent.STEEL_CATWALK_TOP_ALIGNED.getDefaultState(); BlockState place_state = ModContent.STEEL_CATWALK_TOP_ALIGNED.defaultBlockState();
place_state = place_state.with(WATERLOGGED,adjacent_state.getFluidState().getFluid()==Fluids.WATER); place_state = place_state.setValue(WATERLOGGED,adjacent_state.getFluidState().getType()==Fluids.WATER);
EdCatwalkBlock.place_consume(place_state, world, adjacent_pos, player, hand, 1); EdCatwalkBlock.place_consume(place_state, world, adjacent_pos, player, hand, 1);
return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
} else if(block == ModContent.STEEL_RAILING) { } else if(block == ModContent.STEEL_RAILING) {
Direction face = hit.getFace(); Direction face = hit.getDirection();
int shrink = 0; int shrink = 0;
BlockState place_state = state; BlockState place_state = state;
if(face == Direction.UP) { if(face == Direction.UP) {
Vector3d rhv = hit.getHitVec().subtract(Vector3d.copyCentered(hit.getPos())).mul(new Vector3d(1,0,1)).crossProduct(Vector3d.copy(facing.getDirectionVec())); Vector3d rhv = hit.getLocation().subtract(Vector3d.atCenterOf(hit.getBlockPos())).multiply(new Vector3d(1,0,1)).cross(Vector3d.atLowerCornerOf(facing.getNormal()));
face = (rhv.y > 0) ? (facing.rotateY()) : (facing.rotateYCCW()); face = (rhv.y > 0) ? (facing.getClockWise()) : (facing.getCounterClockWise());
} }
if(face == facing.rotateY()) { if(face == facing.getClockWise()) {
if(state.get(RIGHT_RAILING)) { if(state.getValue(RIGHT_RAILING)) {
place_state = state.with(RIGHT_RAILING, false); place_state = state.setValue(RIGHT_RAILING, false);
shrink = -1; shrink = -1;
} else { } else {
place_state = state.with(RIGHT_RAILING, true); place_state = state.setValue(RIGHT_RAILING, true);
shrink = 1; shrink = 1;
} }
} else if(face == facing.rotateYCCW()) { } else if(face == facing.getCounterClockWise()) {
if(state.get(LEFT_RAILING)) { if(state.getValue(LEFT_RAILING)) {
place_state = state.with(LEFT_RAILING, false); place_state = state.setValue(LEFT_RAILING, false);
shrink = -1; shrink = -1;
} else { } else {
place_state = state.with(LEFT_RAILING, true); place_state = state.setValue(LEFT_RAILING, true);
shrink = 1; shrink = 1;
} }
} }
if(shrink != 0) EdCatwalkBlock.place_consume(place_state, world, pos, player, hand, shrink); if(shrink != 0) EdCatwalkBlock.place_consume(place_state, world, pos, player, hand, shrink);
return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
} }
return ActionResultType.PASS; return ActionResultType.PASS;
} }
@ -170,10 +172,10 @@ public class EdCatwalkStairsBlock extends DecorBlock.HorizontalWaterLoggable imp
@Override @Override
public List<ItemStack> dropList(BlockState state, World world, @Nullable TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, @Nullable TileEntity te, boolean explosion)
{ {
if(world.isRemote()) return Collections.singletonList(ItemStack.EMPTY); if(world.isClientSide()) return Collections.singletonList(ItemStack.EMPTY);
List<ItemStack> drops = new ArrayList<>(); List<ItemStack> drops = new ArrayList<>();
drops.add(new ItemStack(state.getBlock().asItem())); drops.add(new ItemStack(state.getBlock().asItem()));
int n = (state.get(LEFT_RAILING)?1:0)+(state.get(RIGHT_RAILING)?1:0); int n = (state.getValue(LEFT_RAILING)?1:0)+(state.getValue(RIGHT_RAILING)?1:0);
if(n > 0) drops.add(new ItemStack(ModContent.STEEL_RAILING, n)); if(n > 0) drops.add(new ItemStack(ModContent.STEEL_RAILING, n));
return drops; return drops;
} }

View file

@ -8,6 +8,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
@ -30,16 +31,17 @@ import javax.annotation.Nullable;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class EdCatwalkTopAlignedBlock extends DecorBlock.WaterLoggable implements IDecorBlock public class EdCatwalkTopAlignedBlock extends DecorBlock.WaterLoggable implements IDecorBlock
{ {
public static final IntegerProperty VARIANT = IntegerProperty.create("variant", 0, 3); public static final IntegerProperty VARIANT = IntegerProperty.create("variant", 0, 3);
protected final List<VoxelShape> variant_shapes; protected final List<VoxelShape> variant_shapes;
public EdCatwalkTopAlignedBlock(long config, Block.Properties properties, final VoxelShape[] variant_shapes) public EdCatwalkTopAlignedBlock(long config, AbstractBlock.Properties properties, final VoxelShape[] variant_shapes)
{ {
super(config, properties, variant_shapes[0]); super(config, properties, variant_shapes[0]);
setDefaultState(super.getDefaultState().with(VARIANT, 0)); registerDefaultState(super.defaultBlockState().setValue(VARIANT, 0));
this.variant_shapes = VARIANT.getAllowedValues().stream().map(i->(i<variant_shapes.length) ? (variant_shapes[i]) : (VoxelShapes.fullCube())).collect(Collectors.toList()); this.variant_shapes = VARIANT.getPossibleValues().stream().map(i->(i<variant_shapes.length) ? (variant_shapes[i]) : (VoxelShapes.block())).collect(Collectors.toList());
} }
@Override @Override
@ -48,56 +50,56 @@ public class EdCatwalkTopAlignedBlock extends DecorBlock.WaterLoggable implement
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return variant_shapes.get(state.get(VARIANT)); } { return variant_shapes.get(state.getValue(VARIANT)); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return getShape(state, world, pos, selectionContext); } { return getShape(state, world, pos, selectionContext); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(VARIANT); } { super.createBlockStateDefinition(builder); builder.add(VARIANT); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
BlockState state = adapted_state(super.getStateForPlacement(context), context.getWorld(), context.getPos()); BlockState state = adapted_state(super.getStateForPlacement(context), context.getLevel(), context.getClickedPos());
if(context.getFace() != Direction.UP) return state; if(context.getClickedFace() != Direction.UP) return state;
BlockState below = context.getWorld().getBlockState(context.getPos().down()); BlockState below = context.getLevel().getBlockState(context.getClickedPos().below());
if((state.get(VARIANT)==0) && (below.isSolidSide(context.getWorld(), context.getPos().down(), Direction.UP))) return state.with(VARIANT, 3); if((state.getValue(VARIANT)==0) && (below.isFaceSturdy(context.getLevel(), context.getClickedPos().below(), Direction.UP))) return state.setValue(VARIANT, 3);
return state; return state;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
final Item item = player.getHeldItem(hand).getItem(); final Item item = player.getItemInHand(hand).getItem();
if(item != this.asItem()) return ActionResultType.PASS; if(item != this.asItem()) return ActionResultType.PASS;
if(hit.getFace().getAxis().isHorizontal()) return ActionResultType.PASS; if(hit.getDirection().getAxis().isHorizontal()) return ActionResultType.PASS;
BlockPos adjacent_pos = pos.offset(player.getHorizontalFacing()); BlockPos adjacent_pos = pos.relative(player.getDirection());
BlockState adjacent_state = world.getBlockState(adjacent_pos); BlockState adjacent_state = world.getBlockState(adjacent_pos);
if(adjacent_state.isReplaceable(new DirectionalPlaceContext(world, adjacent_pos, hit.getFace().getOpposite(), player.getHeldItem(hand), hit.getFace()))) { if(adjacent_state.canBeReplaced(new DirectionalPlaceContext(world, adjacent_pos, hit.getDirection().getOpposite(), player.getItemInHand(hand), hit.getDirection()))) {
BlockState place_state = getDefaultState(); BlockState place_state = defaultBlockState();
place_state = place_state.with(WATERLOGGED,adjacent_state.getFluidState().getFluid()==Fluids.WATER); place_state = place_state.setValue(WATERLOGGED,adjacent_state.getFluidState().getType()==Fluids.WATER);
EdCatwalkBlock.place_consume(adapted_state(place_state, world, adjacent_pos), world, adjacent_pos, player, hand, 1); EdCatwalkBlock.place_consume(adapted_state(place_state, world, adjacent_pos), world, adjacent_pos, player, hand, 1);
} }
return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; return world.isClientSide() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
} }
@Override @Override
public BlockState updatePostPlacement(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos) public BlockState updateShape(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos)
{ return adapted_state(super.updatePostPlacement(state, facing, facingState, world, pos, facingPos), world, pos); } { return adapted_state(super.updateShape(state, facing, facingState, world, pos, facingPos), world, pos); }
// --- // ---
private BlockState adapted_state(BlockState state, IWorld world, BlockPos pos) private BlockState adapted_state(BlockState state, IWorld world, BlockPos pos)
{ {
BlockState below = world.getBlockState(pos.down()); BlockState below = world.getBlockState(pos.below());
if((below == null) || (state == null)) return state; if((below == null) || (state == null)) return state;
if((below.getBlock() == ModContent.THICK_STEEL_POLE) || (below.getBlock() == ModContent.THICK_STEEL_POLE_HEAD)) return state.with(VARIANT, 1); if((below.getBlock() == ModContent.THICK_STEEL_POLE) || (below.getBlock() == ModContent.THICK_STEEL_POLE_HEAD)) return state.setValue(VARIANT, 1);
if((below.getBlock() == ModContent.THIN_STEEL_POLE) || (below.getBlock() == ModContent.THIN_STEEL_POLE_HEAD)) return state.with(VARIANT, 2); if((below.getBlock() == ModContent.THIN_STEEL_POLE) || (below.getBlock() == ModContent.THIN_STEEL_POLE_HEAD)) return state.setValue(VARIANT, 2);
return state; return state;
} }

View file

@ -10,11 +10,9 @@ package wile.engineersdecor.blocks;
import net.minecraft.entity.monster.piglin.PiglinEntity; import net.minecraft.entity.monster.piglin.PiglinEntity;
import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.math.vector.Vector3d;
import wile.engineersdecor.ModConfig; import net.minecraft.block.AbstractBlock;
import wile.engineersdecor.ModContent;
import net.minecraft.world.server.ServerWorld; import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.*; import net.minecraft.entity.*;
@ -25,10 +23,13 @@ import net.minecraft.util.math.*;
import net.minecraft.util.*; import net.minecraft.util.*;
import net.minecraftforge.fml.network.FMLPlayMessages; import net.minecraftforge.fml.network.FMLPlayMessages;
import net.minecraftforge.fml.network.NetworkHooks; import net.minecraftforge.fml.network.NetworkHooks;
import wile.engineersdecor.ModConfig;
import wile.engineersdecor.ModContent;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
public class EdChair public class EdChair
{ {
private static boolean sitting_enabled = true; private static boolean sitting_enabled = true;
@ -49,22 +50,22 @@ public class EdChair
public static class ChairBlock extends DecorBlock.HorizontalWaterLoggable implements IDecorBlock public static class ChairBlock extends DecorBlock.HorizontalWaterLoggable implements IDecorBlock
{ {
public ChairBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABBs) public ChairBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABBs)
{ super(config, builder.tickRandomly(), unrotatedAABBs); } { super(config, builder.randomTicks(), unrotatedAABBs); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(!sitting_enabled) return ActionResultType.PASS; if(!sitting_enabled) return ActionResultType.PASS;
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
EntityChair.sit(world, player, pos); EntityChair.sit(world, player, pos);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void onEntityCollision(BlockState state, World world, BlockPos pos, Entity entity) public void entityInside(BlockState state, World world, BlockPos pos, Entity entity)
{ {
if(sitting_enabled && (Math.random() < sitting_probability) && (entity instanceof MobEntity)) EntityChair.sit(world, (LivingEntity)entity, pos); if(sitting_enabled && (Math.random() < sitting_probability) && (entity instanceof MobEntity)) EntityChair.sit(world, (LivingEntity)entity, pos);
} }
@ -74,7 +75,7 @@ public class EdChair
public void tick(BlockState state, ServerWorld world, BlockPos pos, Random rnd) public void tick(BlockState state, ServerWorld world, BlockPos pos, Random rnd)
{ {
if((!sitting_enabled) || (sitting_probability < 1e-6)) return; if((!sitting_enabled) || (sitting_probability < 1e-6)) return;
final List<LivingEntity> entities = world.getEntitiesWithinAABB(MobEntity.class, new AxisAlignedBB(pos).grow(2,1,2).expand(0,1,0), e->true); final List<LivingEntity> entities = world.getEntitiesOfClass(MobEntity.class, new AxisAlignedBB(pos).inflate(2,1,2).expandTowards(0,1,0), e->true);
if(entities.isEmpty()) return; if(entities.isEmpty()) return;
int index = rnd.nextInt(entities.size()); int index = rnd.nextInt(entities.size());
if((index < 0) || (index >= entities.size())) return; if((index < 0) || (index >= entities.size())) return;
@ -97,10 +98,10 @@ public class EdChair
public EntityChair(EntityType<? extends Entity> entityType, World world) public EntityChair(EntityType<? extends Entity> entityType, World world)
{ {
super(entityType, world); super(entityType, world);
preventEntitySpawning=true; blocksBuilding=true;
setMotion(Vector3d.ZERO); setDeltaMovement(Vector3d.ZERO);
canUpdate(true); canUpdate(true);
noClip=true; noPhysics=true;
} }
public EntityChair(World world) public EntityChair(World world)
@ -109,13 +110,13 @@ public class EdChair
public static EntityChair customClientFactory(FMLPlayMessages.SpawnEntity spkt, World world) public static EntityChair customClientFactory(FMLPlayMessages.SpawnEntity spkt, World world)
{ return new EntityChair(world); } { return new EntityChair(world); }
public IPacket<?> createSpawnPacket() public IPacket<?> getAddEntityPacket()
{ return NetworkHooks.getEntitySpawningPacket(this); } { return NetworkHooks.getEntitySpawningPacket(this); }
public static boolean accepts_mob(LivingEntity entity) public static boolean accepts_mob(LivingEntity entity)
{ {
if(!(entity instanceof net.minecraft.entity.monster.MonsterEntity)) return false; if(!(entity instanceof net.minecraft.entity.monster.MonsterEntity)) return false;
if((entity.getType().getSize().height > 2.5) || (entity.getType().getSize().height > 2.0)) return false; if((entity.getType().getDimensions().height > 2.5) || (entity.getType().getDimensions().height > 2.0)) return false;
if(entity instanceof ZombieEntity) return true; if(entity instanceof ZombieEntity) return true;
if(entity instanceof ZombieVillagerEntity) return true; if(entity instanceof ZombieVillagerEntity) return true;
if(entity instanceof ZombifiedPiglinEntity) return true; if(entity instanceof ZombifiedPiglinEntity) return true;
@ -130,46 +131,46 @@ public class EdChair
public static void sit(World world, LivingEntity sitter, BlockPos pos) public static void sit(World world, LivingEntity sitter, BlockPos pos)
{ {
if(!sitting_enabled) return; if(!sitting_enabled) return;
if((world==null) || (world.isRemote) || (sitter==null) || (pos==null)) return; if((world==null) || (world.isClientSide) || (sitter==null) || (pos==null)) return;
if((!(sitter instanceof PlayerEntity)) && (!accepts_mob(sitter))) return; if((!(sitter instanceof PlayerEntity)) && (!accepts_mob(sitter))) return;
if(!world.getEntitiesWithinAABB(EntityChair.class, new AxisAlignedBB(pos)).isEmpty()) return; if(!world.getEntitiesOfClass(EntityChair.class, new AxisAlignedBB(pos)).isEmpty()) return;
if(sitter.isBeingRidden() || (!sitter.isAlive()) || (sitter.isPassenger()) ) return; if(sitter.isVehicle() || (!sitter.isAlive()) || (sitter.isPassenger()) ) return;
if((!world.isAirBlock(pos.up())) || (!world.isAirBlock(pos.up(2)))) return; if((!world.isEmptyBlock(pos.above())) || (!world.isEmptyBlock(pos.above(2)))) return;
boolean on_top_of_block_position = true; boolean on_top_of_block_position = true;
boolean use_next_negative_y_position = false; boolean use_next_negative_y_position = false;
EntityChair chair = new EntityChair(world); EntityChair chair = new EntityChair(world);
BlockPos chair_pos = chair.getPosition(); BlockPos chair_pos = chair.blockPosition();
chair.chair_pos = pos; chair.chair_pos = pos;
chair.t_sit = 5; chair.t_sit = 5;
chair.prevPosX = chair_pos.getX(); chair.xo = chair_pos.getX();
chair.prevPosY = chair_pos.getY(); chair.yo = chair_pos.getY();
chair.prevPosZ = chair_pos.getZ(); chair.zo = chair_pos.getZ();
chair.setPosition(pos.getX()+x_offset,pos.getY()+y_offset,pos.getZ()+z_offset); chair.setPos(pos.getX()+x_offset,pos.getY()+y_offset,pos.getZ()+z_offset);
world.addEntity(chair); world.addFreshEntity(chair);
sitter.startRiding(chair, true); sitter.startRiding(chair, true);
} }
@Override @Override
protected void registerData() {} protected void defineSynchedData() {}
@Override @Override
protected void readAdditional(CompoundNBT compound) {} protected void readAdditionalSaveData(CompoundNBT compound) {}
@Override @Override
protected void writeAdditional(CompoundNBT compound) {} protected void addAdditionalSaveData(CompoundNBT compound) {}
@Override @Override
public boolean canBePushed() public boolean isPushable()
{ return false; } { return false; }
@Override @Override
public double getMountedYOffset() public double getPassengersRidingOffset()
{ return 0.0; } { return 0.0; }
@Override @Override
public void tick() public void tick()
{ {
if(world.isRemote) return; if(level.isClientSide) return;
super.tick(); super.tick();
if(--t_sit > 0) return; if(--t_sit > 0) return;
Entity sitter = getPassengers().isEmpty() ? null : getPassengers().get(0); Entity sitter = getPassengers().isEmpty() ? null : getPassengers().get(0);
@ -178,9 +179,9 @@ public class EdChair
return; return;
} }
boolean abort = (!sitting_enabled); boolean abort = (!sitting_enabled);
final BlockState state = world.getBlockState(chair_pos); final BlockState state = level.getBlockState(chair_pos);
if((state==null) || (!(state.getBlock() instanceof ChairBlock))) abort = true; if((state==null) || (!(state.getBlock() instanceof ChairBlock))) abort = true;
if(!world.isAirBlock(chair_pos.up())) abort = true; if(!level.isEmptyBlock(chair_pos.above())) abort = true;
if((!(sitter instanceof PlayerEntity)) && (Math.random() < standup_probability)) abort = true; if((!(sitter instanceof PlayerEntity)) && (Math.random() < standup_probability)) abort = true;
if(abort) { if(abort) {
for(Entity e:getPassengers()) { for(Entity e:getPassengers()) {

View file

@ -31,20 +31,20 @@ import java.util.Random;
public class EdChimneyBlock extends DecorBlock.Cutout implements IDecorBlock public class EdChimneyBlock extends DecorBlock.Cutout implements IDecorBlock
{ {
public static final IntegerProperty POWER = BlockStateProperties.POWER_0_15; public static final IntegerProperty POWER = BlockStateProperties.POWER;
public EdChimneyBlock(long config, Block.Properties properties, AxisAlignedBB aabb) public EdChimneyBlock(long config, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ super(config, properties, aabb); } { super(config, properties, aabb); }
public EdChimneyBlock(long config, Block.Properties builder) public EdChimneyBlock(long config, AbstractBlock.Properties builder)
{ {
this(config, builder, new AxisAlignedBB(0,0,0,1,1,1)); this(config, builder, new AxisAlignedBB(0,0,0,1,1,1));
setDefaultState(super.getDefaultState().with(POWER, 0)); // no smoke in JEI registerDefaultState(super.defaultBlockState().setValue(POWER, 0)); // no smoke in JEI
} }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(POWER); } { super.createBlockStateDefinition(builder); builder.add(POWER); }
@Override @Override
@Nullable @Nullable
@ -52,21 +52,21 @@ public class EdChimneyBlock extends DecorBlock.Cutout implements IDecorBlock
{ {
BlockState state = super.getStateForPlacement(context); BlockState state = super.getStateForPlacement(context);
if(state==null) return state; if(state==null) return state;
int p = context.getWorld().getRedstonePowerFromNeighbors(context.getPos()); int p = context.getLevel().getBestNeighborSignal(context.getClickedPos());
return state.with(POWER, p==0 ? 5 : p); return state.setValue(POWER, p==0 ? 5 : p);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ world.setBlockState(pos, state.with(POWER, (state.get(POWER)+1) & 0xf), 1|2); return ActionResultType.func_233537_a_(world.isRemote()); } { world.setBlock(pos, state.setValue(POWER, (state.getValue(POWER)+1) & 0xf), 1|2); return ActionResultType.sidedSuccess(world.isClientSide()); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused)
{ {
int p = world.getRedstonePowerFromNeighbors(pos); int p = world.getBestNeighborSignal(pos);
if(p != state.get(POWER)) world.setBlockState(pos, state.with(POWER, p), 2); if(p != state.getValue(POWER)) world.setBlock(pos, state.setValue(POWER, p), 2);
} }
@Override @Override
@ -78,7 +78,7 @@ public class EdChimneyBlock extends DecorBlock.Cutout implements IDecorBlock
public void animateTick(BlockState state, World world, BlockPos pos, Random rnd) public void animateTick(BlockState state, World world, BlockPos pos, Random rnd)
{ {
if(state.getBlock() != this) return; if(state.getBlock() != this) return;
final int p = state.get(POWER); final int p = state.getValue(POWER);
if(p==0) return; if(p==0) return;
int end = 1+rnd.nextInt(10) * p / 15; int end = 1+rnd.nextInt(10) * p / 15;
for(int i=0; i<end; ++i) { for(int i=0; i<end; ++i) {

View file

@ -20,10 +20,10 @@ import javax.annotation.Nullable;
public class EdChimneyTrunkBlock extends EdRoofBlock implements IDecorBlock public class EdChimneyTrunkBlock extends EdRoofBlock implements IDecorBlock
{ {
public EdChimneyTrunkBlock(long config, Block.Properties properties) public EdChimneyTrunkBlock(long config, AbstractBlock.Properties properties)
{ super(config, properties.variableOpacity(), VoxelShapes.empty(), VoxelShapes.empty()); } { super(config, properties.dynamicShape(), VoxelShapes.empty(), VoxelShapes.empty()); }
public EdChimneyTrunkBlock(long config, Block.Properties properties, VoxelShape add, VoxelShape cut) public EdChimneyTrunkBlock(long config, AbstractBlock.Properties properties, VoxelShape add, VoxelShape cut)
{ super(config, properties, add, cut); } { super(config, properties, add, cut); }
@Override @Override
@ -31,6 +31,6 @@ public class EdChimneyTrunkBlock extends EdRoofBlock implements IDecorBlock
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
BlockState state = super.getStateForPlacement(context); BlockState state = super.getStateForPlacement(context);
return (state==null) ? (state) : (state.with(EdRoofBlock.SHAPE, StairsShape.STRAIGHT).with(EdRoofBlock.HALF, Half.BOTTOM)); return (state==null) ? (state) : (state.setValue(EdRoofBlock.SHAPE, StairsShape.STRAIGHT).setValue(EdRoofBlock.HALF, Half.BOTTOM));
} }
} }

View file

@ -8,6 +8,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.item.BlockItemUseContext; import net.minecraft.item.BlockItemUseContext;
@ -22,11 +23,12 @@ import javax.annotation.Nullable;
import java.util.*; import java.util.*;
public class EdCornerOrnamentedBlock extends DecorBlock.Directed public class EdCornerOrnamentedBlock extends DecorBlock.Directed
{ {
protected final HashSet<Block> compatible_blocks; protected final HashSet<Block> compatible_blocks;
public EdCornerOrnamentedBlock(long config, Block.Properties properties, Block[] assigned_wall_blocks) public EdCornerOrnamentedBlock(long config, AbstractBlock.Properties properties, Block[] assigned_wall_blocks)
{ {
super(config, properties, Auxiliaries.getPixeledAABB(0,0,0,16,16,16)); super(config, properties, Auxiliaries.getPixeledAABB(0,0,0,16,16,16));
compatible_blocks = new HashSet<Block>(Arrays.asList(assigned_wall_blocks)); compatible_blocks = new HashSet<Block>(Arrays.asList(assigned_wall_blocks));
@ -36,25 +38,25 @@ public class EdCornerOrnamentedBlock extends DecorBlock.Directed
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
final World world = context.getWorld(); final World world = context.getLevel();
final BlockPos pos = context.getPos(); final BlockPos pos = context.getClickedPos();
// 1. Placement as below/above for corners, or placement adjacent horizontally if up/down facing. // 1. Placement as below/above for corners, or placement adjacent horizontally if up/down facing.
for(Direction adj: Direction.values()) { for(Direction adj: Direction.values()) {
BlockState state = world.getBlockState(pos.offset(adj)); BlockState state = world.getBlockState(pos.relative(adj));
if(state.getBlock() != this) continue; if(state.getBlock() != this) continue;
Direction facing = state.get(FACING); Direction facing = state.getValue(FACING);
if(facing.getAxis().isHorizontal() == (adj.getAxis().isVertical())) { if(facing.getAxis().isHorizontal() == (adj.getAxis().isVertical())) {
return super.getStateForPlacement(context).with(FACING, state.get(FACING)); return super.getStateForPlacement(context).setValue(FACING, state.getValue(FACING));
} }
} }
// 2. By Player look angles with minimum horizontal diagonal deviation. // 2. By Player look angles with minimum horizontal diagonal deviation.
{ {
Direction facing = Direction.WEST; Direction facing = Direction.WEST;
final Vector2f look = context.getPlayer().getPitchYaw(); final Vector2f look = context.getPlayer().getRotationVector();
final Direction hit_face = context.getFace(); final Direction hit_face = context.getClickedFace();
if((context.getFace()==Direction.DOWN) && (look.x <= -60)) { if((context.getClickedFace()==Direction.DOWN) && (look.x <= -60)) {
facing = Direction.DOWN; facing = Direction.DOWN;
} else if((context.getFace()==Direction.UP) && (look.x >= 60)) { } else if((context.getClickedFace()==Direction.UP) && (look.x >= 60)) {
facing = Direction.UP; facing = Direction.UP;
} else if(MathHelper.degreesDifferenceAbs(look.y, 45) <= 45) { } else if(MathHelper.degreesDifferenceAbs(look.y, 45) <= 45) {
facing = Direction.NORTH; facing = Direction.NORTH;
@ -63,7 +65,7 @@ public class EdCornerOrnamentedBlock extends DecorBlock.Directed
} else if(MathHelper.degreesDifferenceAbs(look.y, 45+180) <= 45) { } else if(MathHelper.degreesDifferenceAbs(look.y, 45+180) <= 45) {
facing = Direction.SOUTH; facing = Direction.SOUTH;
} }
return super.getStateForPlacement(context).with(FACING, facing); return super.getStateForPlacement(context).setValue(FACING, facing);
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -16,16 +16,16 @@ import wile.engineersdecor.libmc.blocks.StandardDoorBlock;
public class EdDoorBlock extends StandardDoorBlock implements IDecorBlock public class EdDoorBlock extends StandardDoorBlock implements IDecorBlock
{ {
public EdDoorBlock(long config, Block.Properties properties, AxisAlignedBB[] open_aabbs_top, AxisAlignedBB[] open_aabbs_bottom, AxisAlignedBB[] closed_aabbs_top, AxisAlignedBB[] closed_aabbs_bottom, SoundEvent open_sound, SoundEvent close_sound) public EdDoorBlock(long config, AbstractBlock.Properties properties, AxisAlignedBB[] open_aabbs_top, AxisAlignedBB[] open_aabbs_bottom, AxisAlignedBB[] closed_aabbs_top, AxisAlignedBB[] closed_aabbs_bottom, SoundEvent open_sound, SoundEvent close_sound)
{ super(config, properties, open_aabbs_top, open_aabbs_bottom, closed_aabbs_top, closed_aabbs_bottom, open_sound, close_sound); } { super(config, properties, open_aabbs_top, open_aabbs_bottom, closed_aabbs_top, closed_aabbs_bottom, open_sound, close_sound); }
public EdDoorBlock(long config, Block.Properties properties, AxisAlignedBB open_aabb, AxisAlignedBB closed_aabb, SoundEvent open_sound, SoundEvent close_sound) public EdDoorBlock(long config, AbstractBlock.Properties properties, AxisAlignedBB open_aabb, AxisAlignedBB closed_aabb, SoundEvent open_sound, SoundEvent close_sound)
{ super(config, properties, open_aabb, closed_aabb, open_sound, close_sound); } { super(config, properties, open_aabb, closed_aabb, open_sound, close_sound); }
public EdDoorBlock(long config, Block.Properties properties, SoundEvent open_sound, SoundEvent close_sound) public EdDoorBlock(long config, AbstractBlock.Properties properties, SoundEvent open_sound, SoundEvent close_sound)
{ super(config, properties, open_sound, close_sound); } { super(config, properties, open_sound, close_sound); }
public EdDoorBlock(long config, Block.Properties properties) public EdDoorBlock(long config, AbstractBlock.Properties properties)
{ super(config, properties); } { super(config, properties); }
} }

View file

@ -30,6 +30,7 @@ import javax.annotation.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
public class EdDoubleGateBlock extends DecorBlock.HorizontalWaterLoggable implements IDecorBlock public class EdDoubleGateBlock extends DecorBlock.HorizontalWaterLoggable implements IDecorBlock
{ {
public static final IntegerProperty SEGMENT = IntegerProperty.create("segment", 0, 1); public static final IntegerProperty SEGMENT = IntegerProperty.create("segment", 0, 1);
@ -38,106 +39,106 @@ public class EdDoubleGateBlock extends DecorBlock.HorizontalWaterLoggable implem
public static final int SEGMENT_UPPER = 1; public static final int SEGMENT_UPPER = 1;
protected final ArrayList<VoxelShape> collision_shapes_; protected final ArrayList<VoxelShape> collision_shapes_;
public EdDoubleGateBlock(long config, Block.Properties properties, AxisAlignedBB aabb) public EdDoubleGateBlock(long config, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ this(config, properties, new AxisAlignedBB[]{aabb}); } { this(config, properties, new AxisAlignedBB[]{aabb}); }
public EdDoubleGateBlock(long config, Block.Properties properties, AxisAlignedBB[] aabbs) public EdDoubleGateBlock(long config, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ {
super(config, properties, aabbs); super(config, properties, aabbs);
AxisAlignedBB[] caabbs = new AxisAlignedBB[aabbs.length]; AxisAlignedBB[] caabbs = new AxisAlignedBB[aabbs.length];
for(int i=0; i<caabbs.length; ++i) caabbs[i] = aabbs[i].expand(0, 0.5, 0); for(int i=0; i<caabbs.length; ++i) caabbs[i] = aabbs[i].expandTowards(0, 0.5, 0);
collision_shapes_ = new ArrayList<VoxelShape>(Arrays.asList( collision_shapes_ = new ArrayList<VoxelShape>(Arrays.asList(
VoxelShapes.fullCube(), VoxelShapes.block(),
VoxelShapes.fullCube(), VoxelShapes.block(),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(caabbs, Direction.NORTH, true)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(caabbs, Direction.NORTH, true)),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(caabbs, Direction.SOUTH, true)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(caabbs, Direction.SOUTH, true)),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(caabbs, Direction.WEST, true)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(caabbs, Direction.WEST, true)),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(caabbs, Direction.EAST, true)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(caabbs, Direction.EAST, true)),
VoxelShapes.fullCube(), VoxelShapes.block(),
VoxelShapes.fullCube() VoxelShapes.block()
)); ));
} }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return state.get(OPEN) ? VoxelShapes.empty() : collision_shapes_.get(state.get(HORIZONTAL_FACING).getIndex() & 0x7); } { return state.getValue(OPEN) ? VoxelShapes.empty() : collision_shapes_.get(state.getValue(HORIZONTAL_FACING).get3DDataValue() & 0x7); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(SEGMENT).add(OPEN); } { super.createBlockStateDefinition(builder); builder.add(SEGMENT).add(OPEN); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return getInitialState(super.getStateForPlacement(context), context.getWorld(), context.getPos()); } { return getInitialState(super.getStateForPlacement(context), context.getLevel(), context.getClickedPos()); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState updatePostPlacement(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos) public BlockState updateShape(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos)
{ return getInitialState(super.updatePostPlacement(state, facing, facingState, world, pos, facingPos), world, pos); } { return getInitialState(super.updateShape(state, facing, facingState, world, pos, facingPos), world, pos); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if((rayTraceResult.getFace()==Direction.UP) || (rayTraceResult.getFace()==Direction.DOWN) && (player.getHeldItem(hand).getItem()==this.asItem())) return ActionResultType.PASS; if((rayTraceResult.getDirection()==Direction.UP) || (rayTraceResult.getDirection()==Direction.DOWN) && (player.getItemInHand(hand).getItem()==this.asItem())) return ActionResultType.PASS;
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
final boolean open = !state.get(OPEN); final boolean open = !state.getValue(OPEN);
world.setBlockState(pos, state.with(OPEN, open),2|8|16); world.setBlock(pos, state.setValue(OPEN, open),2|8|16);
if(state.get(SEGMENT) == SEGMENT_UPPER) { if(state.getValue(SEGMENT) == SEGMENT_UPPER) {
final BlockState adjacent = world.getBlockState(pos.down()); final BlockState adjacent = world.getBlockState(pos.below());
if(adjacent.getBlock()==this) world.setBlockState(pos.down(), adjacent.with(OPEN, open), 2|8|16); if(adjacent.getBlock()==this) world.setBlock(pos.below(), adjacent.setValue(OPEN, open), 2|8|16);
} else { } else {
final BlockState adjacent = world.getBlockState(pos.up()); final BlockState adjacent = world.getBlockState(pos.above());
if(adjacent.getBlock()==this) world.setBlockState(pos.up(), adjacent.with(OPEN, open), 2|8|16); if(adjacent.getBlock()==this) world.setBlock(pos.above(), adjacent.setValue(OPEN, open), 2|8|16);
} }
world.playSound(null, pos, open?SoundEvents.BLOCK_IRON_DOOR_OPEN:SoundEvents.BLOCK_IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 0.7f, 1.4f); world.playSound(null, pos, open?SoundEvents.IRON_DOOR_OPEN:SoundEvents.IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 0.7f, 1.4f);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean allowsMovement(BlockState state, IBlockReader world, BlockPos pos, PathType type) public boolean isPathfindable(BlockState state, IBlockReader world, BlockPos pos, PathType type)
{ return state.get(OPEN); } { return state.getValue(OPEN); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving)
{ {
if(world.isRemote) return; if(world.isClientSide) return;
boolean powered = false; boolean powered = false;
BlockState adjacent; BlockState adjacent;
BlockPos adjacent_pos; BlockPos adjacent_pos;
if(state.get(SEGMENT) == SEGMENT_UPPER) { if(state.getValue(SEGMENT) == SEGMENT_UPPER) {
adjacent_pos = pos.down(); adjacent_pos = pos.below();
adjacent = world.getBlockState(adjacent_pos); adjacent = world.getBlockState(adjacent_pos);
if(adjacent.getBlock()!=this) adjacent = null; if(adjacent.getBlock()!=this) adjacent = null;
if(world.getRedstonePower(pos.up(), Direction.UP) > 0) { if(world.getSignal(pos.above(), Direction.UP) > 0) {
powered = true; powered = true;
} else if((adjacent!=null) && (world.isBlockPowered(pos.down(2)))) { } else if((adjacent!=null) && (world.hasNeighborSignal(pos.below(2)))) {
powered = true; powered = true;
} }
} else { } else {
adjacent_pos = pos.up(); adjacent_pos = pos.above();
adjacent = world.getBlockState(adjacent_pos); adjacent = world.getBlockState(adjacent_pos);
if(adjacent.getBlock()!=this) adjacent = null; if(adjacent.getBlock()!=this) adjacent = null;
if(world.isBlockPowered(pos)) { if(world.hasNeighborSignal(pos)) {
powered = true; powered = true;
} else if((adjacent!=null) && (world.getRedstonePower(pos.up(2), Direction.UP) > 0)) { } else if((adjacent!=null) && (world.getSignal(pos.above(2), Direction.UP) > 0)) {
powered = true; powered = true;
} }
} }
boolean sound = false; boolean sound = false;
if(powered != state.get(OPEN)) { if(powered != state.getValue(OPEN)) {
world.setBlockState(pos, state.with(OPEN, powered), 2|8|16); world.setBlock(pos, state.setValue(OPEN, powered), 2|8|16);
sound = true; sound = true;
} }
if((adjacent != null) && (powered != adjacent.get(OPEN))) { if((adjacent != null) && (powered != adjacent.getValue(OPEN))) {
world.setBlockState(adjacent_pos, adjacent.with(OPEN, powered), 2|8|16); world.setBlock(adjacent_pos, adjacent.setValue(OPEN, powered), 2|8|16);
sound = true; sound = true;
} }
if(sound) { if(sound) {
world.playSound(null, pos, powered?SoundEvents.BLOCK_IRON_DOOR_OPEN:SoundEvents.BLOCK_IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 0.7f, 1.4f); world.playSound(null, pos, powered?SoundEvents.IRON_DOOR_OPEN:SoundEvents.IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 0.7f, 1.4f);
} }
} }
@ -145,11 +146,11 @@ public class EdDoubleGateBlock extends DecorBlock.HorizontalWaterLoggable implem
private BlockState getInitialState(BlockState state, IWorld world, BlockPos pos) private BlockState getInitialState(BlockState state, IWorld world, BlockPos pos)
{ {
final BlockState down = world.getBlockState(pos.down()); final BlockState down = world.getBlockState(pos.below());
if(down.getBlock() == this) return state.with(SEGMENT, SEGMENT_UPPER).with(OPEN, down.get(OPEN)).with(HORIZONTAL_FACING, down.get(HORIZONTAL_FACING)); if(down.getBlock() == this) return state.setValue(SEGMENT, SEGMENT_UPPER).setValue(OPEN, down.getValue(OPEN)).setValue(HORIZONTAL_FACING, down.getValue(HORIZONTAL_FACING));
final BlockState up = world.getBlockState(pos.up()); final BlockState up = world.getBlockState(pos.above());
if(up.getBlock() == this) return state.with(SEGMENT, SEGMENT_LOWER).with(OPEN, up.get(OPEN)).with(HORIZONTAL_FACING, up.get(HORIZONTAL_FACING)); if(up.getBlock() == this) return state.setValue(SEGMENT, SEGMENT_LOWER).setValue(OPEN, up.getValue(OPEN)).setValue(HORIZONTAL_FACING, up.getValue(HORIZONTAL_FACING));
return state.with(SEGMENT, SEGMENT_LOWER).with(OPEN, false); return state.setValue(SEGMENT, SEGMENT_LOWER).setValue(OPEN, false);
} }
} }

View file

@ -8,6 +8,8 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.inventory.container.ClickType; import net.minecraft.inventory.container.ClickType;
import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
@ -15,6 +17,7 @@ import net.minecraft.world.IWorldReader;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.state.BooleanProperty; import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer; import net.minecraft.state.StateContainer;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.DoorBlock; import net.minecraft.block.DoorBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
@ -48,8 +51,6 @@ import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraftforge.items.wrapper.InvWrapper; import net.minecraftforge.items.wrapper.InvWrapper;
import wile.engineersdecor.ModConfig; import wile.engineersdecor.ModConfig;
import wile.engineersdecor.ModContent; import wile.engineersdecor.ModContent;
@ -88,7 +89,7 @@ public class EdDropper
{ {
public static final BooleanProperty OPEN = DoorBlock.OPEN; public static final BooleanProperty OPEN = DoorBlock.OPEN;
public DropperBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB) public DropperBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
@ -97,26 +98,26 @@ public class EdDropper
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return VoxelShapes.fullCube(); } { return VoxelShapes.block(); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(OPEN); } { super.createBlockStateDefinition(builder); builder.add(OPEN); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(OPEN, false); } { return super.getStateForPlacement(context).setValue(OPEN, false); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState blockState, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState blockState, World world, BlockPos pos)
{ return Container.calcRedstone(world.getTileEntity(pos)); } { return Container.getRedstoneSignalFromBlockEntity(world.getBlockEntity(pos)); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -128,17 +129,17 @@ public class EdDropper
{ return new EdDropper.DropperTileEntity(); } { return new EdDropper.DropperTileEntity(); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
if(world.isRemote) return; if(world.isClientSide) return;
if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return; if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return;
CompoundNBT te_nbt = stack.getTag().getCompound("tedata"); CompoundNBT te_nbt = stack.getTag().getCompound("tedata");
if(te_nbt.isEmpty()) return; if(te_nbt.isEmpty()) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof EdDropper.DropperTileEntity)) return; if(!(te instanceof EdDropper.DropperTileEntity)) return;
((EdDropper.DropperTileEntity)te).readnbt(te_nbt, false); ((EdDropper.DropperTileEntity)te).readnbt(te_nbt, false);
((EdDropper.DropperTileEntity)te).reset_rtstate(); ((EdDropper.DropperTileEntity)te).reset_rtstate();
((EdDropper.DropperTileEntity)te).markDirty(); ((EdDropper.DropperTileEntity)te).setChanged();
} }
@Override @Override
@ -149,7 +150,7 @@ public class EdDropper
public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof DropperTileEntity)) return stacks; if(!(te instanceof DropperTileEntity)) return stacks;
if(!explosion) { if(!explosion) {
ItemStack stack = new ItemStack(this, 1); ItemStack stack = new ItemStack(this, 1);
@ -171,10 +172,10 @@ public class EdDropper
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof EdDropper.DropperTileEntity)) return ActionResultType.FAIL; if(!(te instanceof EdDropper.DropperTileEntity)) return ActionResultType.FAIL;
if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL; if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL;
NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te); NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te);
@ -185,8 +186,8 @@ public class EdDropper
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused)
{ {
if(!(world instanceof World) || (((World) world).isRemote)) return; if(!(world instanceof World) || (((World) world).isClientSide)) return;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof DropperTileEntity)) return; if(!(te instanceof DropperTileEntity)) return;
((DropperTileEntity)te).block_updated(); ((DropperTileEntity)te).block_updated();
} }
@ -220,7 +221,7 @@ public class EdDropper
public static final int DROPLOGIC_CONTINUOUS = 0x10; public static final int DROPLOGIC_CONTINUOUS = 0x10;
public static final int DROPLOGIC_IGNORE_EXT = 0x20; public static final int DROPLOGIC_IGNORE_EXT = 0x20;
/// ///
private int filter_matches_[] = new int[CTRL_SLOTS_SIZE]; private final int filter_matches_[] = new int[CTRL_SLOTS_SIZE];
private int open_timer_ = 0; private int open_timer_ = 0;
private int drop_timer_ = 0; private int drop_timer_ = 0;
private boolean triggered_ = false; private boolean triggered_ = false;
@ -249,7 +250,7 @@ public class EdDropper
{ {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
writenbt(nbt, false); writenbt(nbt, false);
main_inventory_.clear(); main_inventory_.clearContent();
reset_rtstate(); reset_rtstate();
triggered_ = false; triggered_ = false;
block_power_updated_ = false; block_power_updated_ = false;
@ -260,7 +261,7 @@ public class EdDropper
{ {
block_power_signal_ = false; block_power_signal_ = false;
block_power_updated_ = false; block_power_updated_ = false;
for(int i=0; i<filter_matches_.length; ++i) filter_matches_[i] = 0; Arrays.fill(filter_matches_, 0);
} }
public void readnbt(CompoundNBT nbt, boolean update_packet) public void readnbt(CompoundNBT nbt, boolean update_packet)
@ -296,7 +297,7 @@ public class EdDropper
public void block_updated() public void block_updated()
{ {
// RS power check, both edges // RS power check, both edges
boolean powered = world.isBlockPowered(pos); boolean powered = level.hasNeighborSignal(worldPosition);
if(block_power_signal_ != powered) block_power_updated_ = true; if(block_power_signal_ != powered) block_power_updated_ = true;
block_power_signal_ = powered; block_power_signal_ = powered;
tick_timer_ = 1; tick_timer_ = 1;
@ -308,17 +309,17 @@ public class EdDropper
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt, false); } { super.load(state, nbt); readnbt(nbt, false); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt, false); return nbt; } { super.save(nbt); writenbt(nbt, false); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
item_handler_.invalidate(); item_handler_.invalidate();
} }
@ -326,7 +327,7 @@ public class EdDropper
@Override @Override
public ITextComponent getName() public ITextComponent getName()
{ final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getTranslationKey() : "Factory dropper"); } { final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getDescriptionId() : "Factory dropper"); }
@Override @Override
public boolean hasCustomName() public boolean hasCustomName()
@ -344,7 +345,7 @@ public class EdDropper
@Override @Override
public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player ) public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player )
{ return new DropperContainer(id, inventory, main_inventory_, IWorldPosCallable.of(world, pos), fields); } { return new DropperUiContainer(id, inventory, main_inventory_, IWorldPosCallable.create(level, worldPosition), fields); }
// Fields ----------------------------------------------------------------------------------------------- // Fields -----------------------------------------------------------------------------------------------
@ -410,7 +411,7 @@ public class EdDropper
private static void drop(World world, BlockPos pos, Direction facing, ItemStack stack, int speed_percent, int xdeviation, int ydeviation, int noise_percent) private static void drop(World world, BlockPos pos, Direction facing, ItemStack stack, int speed_percent, int xdeviation, int ydeviation, int noise_percent)
{ {
final double ofs = facing==Direction.DOWN ? 0.8 : 0.7; final double ofs = facing==Direction.DOWN ? 0.8 : 0.7;
Vector3d v0 = new Vector3d(facing.getXOffset(), facing.getYOffset(), facing.getZOffset()); Vector3d v0 = new Vector3d(facing.getStepX(), facing.getStepY(), facing.getStepZ());
final ItemEntity ei = new ItemEntity(world, (pos.getX()+0.5)+(ofs*v0.x), (pos.getY()+0.5)+(ofs*v0.y), (pos.getZ()+0.5)+(ofs*v0.z), stack); final ItemEntity ei = new ItemEntity(world, (pos.getX()+0.5)+(ofs*v0.x), (pos.getY()+0.5)+(ofs*v0.y), (pos.getZ()+0.5)+(ofs*v0.z), stack);
if((xdeviation != 0) || (ydeviation != 0)) { if((xdeviation != 0) || (ydeviation != 0)) {
double vdx = 1e-2 * MathHelper.clamp(xdeviation, -100, 100); double vdx = 1e-2 * MathHelper.clamp(xdeviation, -100, 100);
@ -426,25 +427,25 @@ public class EdDropper
} }
if(noise_percent > 0) { if(noise_percent > 0) {
v0 = v0.add( v0 = v0.add(
((world.rand.nextDouble()-0.5) * 1e-3 * noise_percent), ((world.random.nextDouble()-0.5) * 1e-3 * noise_percent),
((world.rand.nextDouble()-0.5) * 1e-3 * noise_percent), ((world.random.nextDouble()-0.5) * 1e-3 * noise_percent),
((world.rand.nextDouble()-0.5) * 1e-3 * noise_percent) ((world.random.nextDouble()-0.5) * 1e-3 * noise_percent)
); );
} }
if(speed_percent < 5) speed_percent = 5; if(speed_percent < 5) speed_percent = 5;
double speed = 1e-2 * speed_percent; double speed = 1e-2 * speed_percent;
if(noise_percent > 0) speed += (world.rand.nextDouble()-0.5) * 1e-4 * noise_percent; if(noise_percent > 0) speed += (world.random.nextDouble()-0.5) * 1e-4 * noise_percent;
v0 = v0.normalize().scale(speed); v0 = v0.normalize().scale(speed);
ei.setMotion(v0.x, v0.y, v0.z); ei.setDeltaMovement(v0.x, v0.y, v0.z);
ei.velocityChanged = true; ei.hurtMarked = true;
world.addEntity(ei); world.addFreshEntity(ei);
} }
private static Tuple<Boolean, List<ItemStack>> try_eject(World world, BlockPos pos, Direction facing, ItemStack[] stacks, int speed_percent, int xdeviation, int ydeviation, int noise_percent) private static Tuple<Boolean, List<ItemStack>> try_eject(World world, BlockPos pos, Direction facing, ItemStack[] stacks, int speed_percent, int xdeviation, int ydeviation, int noise_percent)
{ {
if(Arrays.stream(stacks).allMatch(e->e.isEmpty())) return new Tuple<>(false, Arrays.asList(stacks)); if(Arrays.stream(stacks).allMatch(e->e.isEmpty())) return new Tuple<>(false, Arrays.asList(stacks));
if(with_adjacent_item_insertion) { if(with_adjacent_item_insertion) {
final TileEntity te = world.getTileEntity(pos.offset(facing)); final TileEntity te = world.getBlockEntity(pos.relative(facing));
if(te != null) { if(te != null) {
final IItemHandler ih = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, (facing==null)?(null):(facing.getOpposite())).orElse(null); final IItemHandler ih = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, (facing==null)?(null):(facing.getOpposite())).orElse(null);
if(ih != null) { if(ih != null) {
@ -471,17 +472,17 @@ public class EdDropper
@Nullable @Nullable
BlockState update_blockstate() BlockState update_blockstate()
{ {
BlockState state = world.getBlockState(pos); BlockState state = level.getBlockState(worldPosition);
if(!(state.getBlock() instanceof DropperBlock)) return null; if(!(state.getBlock() instanceof DropperBlock)) return null;
boolean open = (open_timer_ > 0); boolean open = (open_timer_ > 0);
if(state.get(DropperBlock.OPEN) != open) { if(state.getValue(DropperBlock.OPEN) != open) {
state = state.with(DropperBlock.OPEN, open); state = state.setValue(DropperBlock.OPEN, open);
world.setBlockState(pos, state, 2|16); level.setBlock(worldPosition, state, 2|16);
if((drop_logic_ & DROPLOGIC_SILENT_OPEN) == 0) { if((drop_logic_ & DROPLOGIC_SILENT_OPEN) == 0) {
if(open) { if(open) {
world.playSound(null, pos, SoundEvents.BLOCK_WOODEN_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 0.08f, 3f); level.playSound(null, worldPosition, SoundEvents.WOODEN_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 0.08f, 3f);
} else { } else {
world.playSound(null, pos, SoundEvents.BLOCK_WOODEN_TRAPDOOR_CLOSE, SoundCategory.BLOCKS, 0.08f, 3f); level.playSound(null, worldPosition, SoundEvents.WOODEN_TRAPDOOR_CLOSE, SoundCategory.BLOCKS, 0.08f, 3f);
} }
} }
} }
@ -494,12 +495,12 @@ public class EdDropper
@Override @Override
public void tick() public void tick()
{ {
if(world.isRemote) return; if(level.isClientSide) return;
if(--open_timer_ < 0) open_timer_ = 0; if(--open_timer_ < 0) open_timer_ = 0;
if((drop_timer_ > 0) && ((--drop_timer_) == 0)) markDirty(); if((drop_timer_ > 0) && ((--drop_timer_) == 0)) setChanged();
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
if(!(world.getBlockState(pos).getBlock() instanceof DropperBlock)) return; if(!(level.getBlockState(worldPosition).getBlock() instanceof DropperBlock)) return;
if(storage_slot_range_.isEmpty()) return; if(storage_slot_range_.isEmpty()) return;
final boolean continuous_mode = (drop_logic_ & DROPLOGIC_CONTINUOUS)!=0; final boolean continuous_mode = (drop_logic_ & DROPLOGIC_CONTINUOUS)!=0;
boolean dirty = block_power_updated_; boolean dirty = block_power_updated_;
@ -515,7 +516,7 @@ public class EdDropper
int last_filter_matches_[] = filter_matches_.clone(); int last_filter_matches_[] = filter_matches_.clone();
for(int ci=0; ci<CTRL_SLOTS_SIZE; ++ci) { for(int ci=0; ci<CTRL_SLOTS_SIZE; ++ci) {
filter_matches_[ci] = 0; filter_matches_[ci] = 0;
final ItemStack cmp_stack = main_inventory_.getStackInSlot(CTRL_SLOTS_FIRST+ci); final ItemStack cmp_stack = main_inventory_.getItem(CTRL_SLOTS_FIRST+ci);
if(cmp_stack.isEmpty()) continue; if(cmp_stack.isEmpty()) continue;
filter_matches_[ci] = 1; filter_matches_[ci] = 1;
final int cmp_stack_count = cmp_stack.getCount(); final int cmp_stack_count = cmp_stack.getCount();
@ -555,7 +556,7 @@ public class EdDropper
} }
// edge detection for next cycle // edge detection for next cycle
{ {
boolean tr = world.isBlockPowered(pos); boolean tr = level.hasNeighborSignal(worldPosition);
block_power_updated_ = (block_power_signal_ != tr); block_power_updated_ = (block_power_signal_ != tr);
block_power_signal_ = tr; block_power_signal_ = tr;
if(block_power_updated_) dirty = true; if(block_power_updated_) dirty = true;
@ -573,34 +574,34 @@ public class EdDropper
if(drop_slot_index_ >= INPUT_SLOTS_SIZE) drop_slot_index_ = 0; if(drop_slot_index_ >= INPUT_SLOTS_SIZE) drop_slot_index_ = 0;
final int ic = drop_slot_index_; final int ic = drop_slot_index_;
drop_slot_index_ = next_slot(drop_slot_index_); drop_slot_index_ = next_slot(drop_slot_index_);
ItemStack ds = main_inventory_.getStackInSlot(ic); ItemStack ds = main_inventory_.getItem(ic);
if((!ds.isEmpty()) && (ds.getCount() >= drop_count_)) { if((!ds.isEmpty()) && (ds.getCount() >= drop_count_)) {
boolean skip_stack = false; boolean skip_stack = false;
for(int ci = 0; (ci<CTRL_SLOTS_SIZE)&&(!skip_stack); ++ci) { for(int ci = 0; (ci<CTRL_SLOTS_SIZE)&&(!skip_stack); ++ci) {
final ItemStack cmp_stack = main_inventory_.getStackInSlot(CTRL_SLOTS_FIRST+ci); final ItemStack cmp_stack = main_inventory_.getItem(CTRL_SLOTS_FIRST+ci);
if(Inventories.areItemStacksIdentical(ds, cmp_stack)) skip_stack = true; if(Inventories.areItemStacksIdentical(ds, cmp_stack)) skip_stack = true;
} }
if(skip_stack) continue; if(skip_stack) continue;
drop_stacks[0] = ds.split(drop_count_); drop_stacks[0] = ds.split(drop_count_);
main_inventory_.setInventorySlotContents(ic, ds); main_inventory_.setItem(ic, ds);
break; break;
} }
} }
} else { } else {
for(int fi=0; fi<filter_matches_.length; ++fi) { for(int fi=0; fi<filter_matches_.length; ++fi) {
if(filter_matches_[fi] > 1) { if(filter_matches_[fi] > 1) {
drop_stacks[fi] = main_inventory_.getStackInSlot(CTRL_SLOTS_FIRST+fi).copy(); drop_stacks[fi] = main_inventory_.getItem(CTRL_SLOTS_FIRST+fi).copy();
int ntoremove = drop_stacks[fi].getCount(); int ntoremove = drop_stacks[fi].getCount();
for(int i=INPUT_SLOTS_SIZE-1; (i>=0) && (ntoremove>0); --i) { for(int i=INPUT_SLOTS_SIZE-1; (i>=0) && (ntoremove>0); --i) {
ItemStack stack = main_inventory_.getStackInSlot(i); ItemStack stack = main_inventory_.getItem(i);
if(Inventories.areItemStacksDifferent(stack, drop_stacks[fi])) continue; if(Inventories.areItemStacksDifferent(stack, drop_stacks[fi])) continue;
if(stack.getCount() <= ntoremove) { if(stack.getCount() <= ntoremove) {
ntoremove -= stack.getCount(); ntoremove -= stack.getCount();
main_inventory_.setInventorySlotContents(i, ItemStack.EMPTY); main_inventory_.setItem(i, ItemStack.EMPTY);
} else { } else {
stack.shrink(ntoremove); stack.shrink(ntoremove);
ntoremove = 0; ntoremove = 0;
main_inventory_.setInventorySlotContents(i, stack); main_inventory_.setItem(i, stack);
} }
} }
if(ntoremove > 0) drop_stacks[fi].shrink(ntoremove); if(ntoremove > 0) drop_stacks[fi].shrink(ntoremove);
@ -611,7 +612,7 @@ public class EdDropper
if(Arrays.stream(drop_stacks).allMatch(ItemStack::isEmpty)) { if(Arrays.stream(drop_stacks).allMatch(ItemStack::isEmpty)) {
// @todo: check if a re-stacking action is appropriate, or if players intentionally use the stack-in-place feature. // @todo: check if a re-stacking action is appropriate, or if players intentionally use the stack-in-place feature.
} else { } else {
Tuple<Boolean, List<ItemStack>> res = try_eject(world, pos, state.get(DropperBlock.FACING), drop_stacks, drop_speed_, drop_xdev_, drop_ydev_, drop_noise_); Tuple<Boolean, List<ItemStack>> res = try_eject(level, worldPosition, state.getValue(DropperBlock.FACING), drop_stacks, drop_speed_, drop_xdev_, drop_ydev_, drop_noise_);
final boolean dropped = res.getA(); final boolean dropped = res.getA();
final List<ItemStack> remaining = res.getB(); final List<ItemStack> remaining = res.getB();
for(ItemStack st:remaining) { for(ItemStack st:remaining) {
@ -622,20 +623,20 @@ public class EdDropper
if(dropped) drop_timer_ = DROP_PERIOD_OFFSET + drop_period_ * 2; // 0.1s time base -> 100%===10s if(dropped) drop_timer_ = DROP_PERIOD_OFFSET + drop_period_ * 2; // 0.1s time base -> 100%===10s
// drop sound // drop sound
if(dropped && ((drop_logic_ & DROPLOGIC_SILENT_DROP) == 0)) { if(dropped && ((drop_logic_ & DROPLOGIC_SILENT_DROP) == 0)) {
world.playSound(null, pos, SoundEvents.BLOCK_WOOD_HIT, SoundCategory.BLOCKS, 0.1f, 4f); level.playSound(null, worldPosition, SoundEvents.WOOD_HIT, SoundCategory.BLOCKS, 0.1f, 4f);
} }
} }
// advance to next nonempty slot. // advance to next nonempty slot.
{ {
boolean found = false; boolean found = false;
for(int i = 0; i < storage_slot_range_.size; ++i) { for(int i = 0; i < storage_slot_range_.size; ++i) {
if(!main_inventory_.getStackInSlot(drop_slot_index_).isEmpty()) { found=true; break; } if(!main_inventory_.getItem(drop_slot_index_).isEmpty()) { found=true; break; }
drop_slot_index_ = next_slot(drop_slot_index_); drop_slot_index_ = next_slot(drop_slot_index_);
} }
if(!found) drop_slot_index_ = 0; if(!found) drop_slot_index_ = 0;
} }
} }
if(dirty) markDirty(); if(dirty) setChanged();
if(trigger && (tick_timer_ > 10)) tick_timer_ = 10; if(trigger && (tick_timer_ > 10)) tick_timer_ = 10;
} }
} }
@ -644,7 +645,7 @@ public class EdDropper
// Container // Container
//-------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------
public static class DropperContainer extends Container implements Networking.INetworkSynchronisableContainer public static class DropperUiContainer extends Container implements Networking.INetworkSynchronisableContainer
{ {
protected static final String QUICK_MOVE_ALL = "quick-move-all"; protected static final String QUICK_MOVE_ALL = "quick-move-all";
private static final int PLAYER_INV_START_SLOTNO = DropperTileEntity.NUM_OF_SLOTS; private static final int PLAYER_INV_START_SLOTNO = DropperTileEntity.NUM_OF_SLOTS;
@ -657,10 +658,10 @@ public class EdDropper
public final int field(int index) { return fields_.get(index); } public final int field(int index) { return fields_.get(index); }
public DropperContainer(int cid, PlayerInventory player_inventory) public DropperUiContainer(int cid, PlayerInventory player_inventory)
{ this(cid, player_inventory, new Inventory(DropperTileEntity.NUM_OF_SLOTS), IWorldPosCallable.DUMMY, new IntArray(DropperTileEntity.NUM_OF_FIELDS)); } { this(cid, player_inventory, new Inventory(DropperTileEntity.NUM_OF_SLOTS), IWorldPosCallable.NULL, new IntArray(DropperTileEntity.NUM_OF_FIELDS)); }
private DropperContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields) private DropperUiContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields)
{ {
super(ModContent.CT_FACTORY_DROPPER, cid); super(ModContent.CT_FACTORY_DROPPER, cid);
fields_ = fields; fields_ = fields;
@ -690,34 +691,34 @@ public class EdDropper
addSlot(new Slot(player_inventory, x+y*9+9, 8+x*18, 86+y*18)); // player slots: 9..35 addSlot(new Slot(player_inventory, x+y*9+9, 8+x*18, 86+y*18)); // player slots: 9..35
} }
} }
this.trackIntArray(fields_); // === Add reference holders this.addDataSlots(fields_); // === Add reference holders
} }
@Override @Override
public boolean canInteractWith(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return inventory_.isUsableByPlayer(player); } { return inventory_.stillValid(player); }
@Override @Override
public ItemStack transferStackInSlot(PlayerEntity player, int index) public ItemStack quickMoveStack(PlayerEntity player, int index)
{ {
Slot slot = getSlot(index); Slot slot = getSlot(index);
if((slot==null) || (!slot.getHasStack())) return ItemStack.EMPTY; if((slot==null) || (!slot.hasItem())) return ItemStack.EMPTY;
ItemStack slot_stack = slot.getStack(); ItemStack slot_stack = slot.getItem();
ItemStack transferred = slot_stack.copy(); ItemStack transferred = slot_stack.copy();
if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) { if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) {
// Device slots // Device slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) {
// Player slot // Player slot
if(!mergeItemStack(slot_stack, 0, DropperTileEntity.INPUT_SLOTS_SIZE, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, 0, DropperTileEntity.INPUT_SLOTS_SIZE, false)) return ItemStack.EMPTY;
} else { } else {
// invalid slot // invalid slot
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
if(slot_stack.isEmpty()) { if(slot_stack.isEmpty()) {
slot.putStack(ItemStack.EMPTY); slot.set(ItemStack.EMPTY);
} else { } else {
slot.onSlotChanged(); slot.setChanged();
} }
if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY; if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY;
slot.onTake(player, slot_stack); slot.onTake(player, slot_stack);
@ -728,21 +729,21 @@ public class EdDropper
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(CompoundNBT nbt) public void onGuiAction(CompoundNBT nbt)
{ Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); } { Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt); }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(String key, int value) public void onGuiAction(String key, int value)
{ {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt(key, value); nbt.putInt(key, value);
Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt);
} }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(String message, CompoundNBT nbt) public void onGuiAction(String message, CompoundNBT nbt)
{ {
nbt.putString("action", message); nbt.putString("action", message);
Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt);
} }
@Override @Override
@ -758,17 +759,17 @@ public class EdDropper
final int slotId = nbt.contains("slot") ? nbt.getInt("slot") : -1; final int slotId = nbt.contains("slot") ? nbt.getInt("slot") : -1;
switch(nbt.getString("action")) { switch(nbt.getString("action")) {
case QUICK_MOVE_ALL: { case QUICK_MOVE_ALL: {
if((slotId >= 0) && (slotId < PLAYER_INV_START_SLOTNO) && (getSlot(slotId).getHasStack())) { if((slotId >= 0) && (slotId < PLAYER_INV_START_SLOTNO) && (getSlot(slotId).hasItem())) {
changed = block_storage_range_.move(getSlot(slotId).getSlotIndex(), player_inventory_range_, true, false, true, true); changed = block_storage_range_.move(getSlot(slotId).getSlotIndex(), player_inventory_range_, true, false, true, true);
} else if((slotId >= PLAYER_INV_START_SLOTNO) && (slotId < PLAYER_INV_START_SLOTNO+36) && (getSlot(slotId).getHasStack())) { } else if((slotId >= PLAYER_INV_START_SLOTNO) && (slotId < PLAYER_INV_START_SLOTNO+36) && (getSlot(slotId).hasItem())) {
changed = player_inventory_range_.move(getSlot(slotId).getSlotIndex(), block_storage_range_, true, false, false, true); changed = player_inventory_range_.move(getSlot(slotId).getSlotIndex(), block_storage_range_, true, false, false, true);
} }
} break; } break;
} }
if(changed) { if(changed) {
inventory_.markDirty(); inventory_.setChanged();
player.inventory.markDirty(); player.inventory.setChanged();
detectAndSendChanges(); broadcastChanges();
} }
} else { } else {
DropperTileEntity te = (DropperTileEntity)((StorageInventory)inventory_).getTileEntity(); DropperTileEntity te = (DropperTileEntity)((StorageInventory)inventory_).getTileEntity();
@ -780,7 +781,7 @@ public class EdDropper
if(nbt.contains("drop_logic")) te.drop_logic_ = nbt.getInt("drop_logic"); if(nbt.contains("drop_logic")) te.drop_logic_ = nbt.getInt("drop_logic");
if(nbt.contains("manual_rstrigger") && (nbt.getInt("manual_rstrigger")!=0)) { te.block_power_signal_=true; te.block_power_updated_=true; te.tick_timer_=1; } if(nbt.contains("manual_rstrigger") && (nbt.getInt("manual_rstrigger")!=0)) { te.block_power_signal_=true; te.block_power_updated_=true; te.tick_timer_=1; }
if(nbt.contains("manual_trigger") && (nbt.getInt("manual_trigger")!=0)) { te.tick_timer_ = 1; te.triggered_ = true; } if(nbt.contains("manual_trigger") && (nbt.getInt("manual_trigger")!=0)) { te.tick_timer_ = 1; te.triggered_ = true; }
te.markDirty(); te.setChanged();
} }
} }
@ -791,12 +792,12 @@ public class EdDropper
//-------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public static class DropperGui extends ContainerGui<DropperContainer> public static class DropperGui extends ContainerGui<DropperUiContainer>
{ {
protected final PlayerEntity player_; protected final PlayerEntity player_;
protected final TooltipDisplay tooltip_ = new TooltipDisplay(); protected final TooltipDisplay tooltip_ = new TooltipDisplay();
public DropperGui(DropperContainer container, PlayerInventory player_inventory, ITextComponent title) public DropperGui(DropperUiContainer container, PlayerInventory player_inventory, ITextComponent title)
{ super(container, player_inventory, title); this.player_ = player_inventory.player; } { super(container, player_inventory, title); this.player_ = player_inventory.player; }
@Override @Override
@ -804,7 +805,7 @@ public class EdDropper
{ {
super.init(); super.init();
{ {
final String prefix = ModContent.FACTORY_DROPPER.getTranslationKey() + ".tooltips."; final String prefix = ModContent.FACTORY_DROPPER.getDescriptionId() + ".tooltips.";
final int x0 = getGuiLeft(), y0 = getGuiTop(); final int x0 = getGuiLeft(), y0 = getGuiTop();
tooltip_.init( tooltip_.init(
new TipRange(x0+130, y0+10, 12, 25, new TranslationTextComponent(prefix + "velocity")), new TipRange(x0+130, y0+10, 12, 25, new TranslationTextComponent(prefix + "velocity")),
@ -824,25 +825,25 @@ public class EdDropper
{ {
renderBackground(mx); renderBackground(mx);
super.render(mx, mouseX, mouseY, partialTicks); super.render(mx, mouseX, mouseY, partialTicks);
if(!tooltip_.render(mx, this, mouseX, mouseY)) renderHoveredTooltip(mx, mouseX, mouseY); if(!tooltip_.render(mx, this, mouseX, mouseY)) renderTooltip(mx, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerForegroundLayer(MatrixStack mx, int x, int y) protected void renderLabels(MatrixStack mx, int x, int y)
{} {}
@Override @Override
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) public boolean mouseClicked(double mouseX, double mouseY, int mouseButton)
{ {
tooltip_.resetTimer(); tooltip_.resetTimer();
DropperContainer container = (DropperContainer)getContainer(); DropperUiContainer container = (DropperUiContainer)getMenu();
int mx = (int)(mouseX - getGuiLeft() + .5), my = (int)(mouseY - getGuiTop() + .5); int mx = (int)(mouseX - getGuiLeft() + .5), my = (int)(mouseY - getGuiTop() + .5);
if((!isPointInRegion(114, 1, 61, 79, mouseX, mouseY))) { if((!isHovering(114, 1, 61, 79, mouseX, mouseY))) {
return super.mouseClicked(mouseX, mouseY, mouseButton); return super.mouseClicked(mouseX, mouseY, mouseButton);
} else if(isPointInRegion(130, 10, 12, 25, mouseX, mouseY)) { } else if(isHovering(130, 10, 12, 25, mouseX, mouseY)) {
int force_percent = 100 - MathHelper.clamp(((my-10)*100)/25, 0, 100); int force_percent = 100 - MathHelper.clamp(((my-10)*100)/25, 0, 100);
container.onGuiAction("drop_speed", force_percent); container.onGuiAction("drop_speed", force_percent);
} else if(isPointInRegion(145, 10, 25, 25, mouseX, mouseY)) { } else if(isHovering(145, 10, 25, 25, mouseX, mouseY)) {
int xdev = MathHelper.clamp( (int)Math.round(((double)((mx-157) * 100)) / 12), -100, 100); int xdev = MathHelper.clamp( (int)Math.round(((double)((mx-157) * 100)) / 12), -100, 100);
int ydev = MathHelper.clamp(-(int)Math.round(((double)((my- 22) * 100)) / 12), -100, 100); int ydev = MathHelper.clamp(-(int)Math.round(((double)((my- 22) * 100)) / 12), -100, 100);
if(Math.abs(xdev) < 9) xdev = 0; if(Math.abs(xdev) < 9) xdev = 0;
@ -851,7 +852,7 @@ public class EdDropper
nbt.putInt("drop_xdev", xdev); nbt.putInt("drop_xdev", xdev);
nbt.putInt("drop_ydev", ydev); nbt.putInt("drop_ydev", ydev);
container.onGuiAction(nbt); container.onGuiAction(nbt);
} else if(isPointInRegion(129, 40, 44, 10, mouseX, mouseY)) { } else if(isHovering(129, 40, 44, 10, mouseX, mouseY)) {
int ndrop = (mx-135); int ndrop = (mx-135);
if(ndrop < -1) { if(ndrop < -1) {
ndrop = container.field(4) - 1; // - ndrop = container.field(4) - 1; // -
@ -861,7 +862,7 @@ public class EdDropper
ndrop = MathHelper.clamp(1+ndrop, 1, DropperTileEntity.MAX_DROP_COUNT); // slider ndrop = MathHelper.clamp(1+ndrop, 1, DropperTileEntity.MAX_DROP_COUNT); // slider
} }
container.onGuiAction("drop_count", ndrop); container.onGuiAction("drop_count", ndrop);
} else if(isPointInRegion(129, 50, 44, 10, mouseX, mouseY)) { } else if(isHovering(129, 50, 44, 10, mouseX, mouseY)) {
int period = (mx-135); int period = (mx-135);
if(period < -1) { if(period < -1) {
period = container.field(6) - 3; // - period = container.field(6) - 3; // -
@ -872,13 +873,13 @@ public class EdDropper
} }
period = MathHelper.clamp(period, 0, 100); period = MathHelper.clamp(period, 0, 100);
container.onGuiAction("drop_period", period); container.onGuiAction("drop_period", period);
} else if(isPointInRegion(114, 51, 9, 9, mouseX, mouseY)) { } else if(isHovering(114, 51, 9, 9, mouseX, mouseY)) {
container.onGuiAction("manual_rstrigger", 1); container.onGuiAction("manual_rstrigger", 1);
} else if(isPointInRegion(162, 66, 7, 9, mouseX, mouseY)) { } else if(isHovering(162, 66, 7, 9, mouseX, mouseY)) {
container.onGuiAction("drop_logic", container.field(5) ^ DropperTileEntity.DROPLOGIC_CONTINUOUS); container.onGuiAction("drop_logic", container.field(5) ^ DropperTileEntity.DROPLOGIC_CONTINUOUS);
} else if(isPointInRegion(132, 66, 9, 9, mouseX, mouseY)) { } else if(isHovering(132, 66, 9, 9, mouseX, mouseY)) {
container.onGuiAction("drop_logic", container.field(5) ^ DropperTileEntity.DROPLOGIC_FILTER_ANDGATE); container.onGuiAction("drop_logic", container.field(5) ^ DropperTileEntity.DROPLOGIC_FILTER_ANDGATE);
} else if(isPointInRegion(148, 66, 9, 9, mouseX, mouseY)) { } else if(isHovering(148, 66, 9, 9, mouseX, mouseY)) {
final int mask = (DropperTileEntity.DROPLOGIC_EXTERN_ANDGATE|DropperTileEntity.DROPLOGIC_IGNORE_EXT); final int mask = (DropperTileEntity.DROPLOGIC_EXTERN_ANDGATE|DropperTileEntity.DROPLOGIC_IGNORE_EXT);
int logic = (container.field(5) & mask); int logic = (container.field(5) & mask);
switch(logic) { switch(logic) {
@ -893,28 +894,28 @@ public class EdDropper
} }
@Override @Override
protected void handleMouseClick(Slot slot, int slotId, int button, ClickType type) protected void slotClicked(Slot slot, int slotId, int button, ClickType type)
{ {
tooltip_.resetTimer(); tooltip_.resetTimer();
if((type == ClickType.QUICK_MOVE) && (slot!=null) && slot.getHasStack() && Auxiliaries.isShiftDown() && Auxiliaries.isCtrlDown()) { if((type == ClickType.QUICK_MOVE) && (slot!=null) && slot.hasItem() && Auxiliaries.isShiftDown() && Auxiliaries.isCtrlDown()) {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt("slot", slotId); nbt.putInt("slot", slotId);
container.onGuiAction(DropperContainer.QUICK_MOVE_ALL, nbt); menu.onGuiAction(DropperUiContainer.QUICK_MOVE_ALL, nbt);
} else { } else {
super.handleMouseClick(slot, slotId, button, type); super.slotClicked(slot, slotId, button, type);
} }
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void drawGuiContainerBackgroundLayer(MatrixStack mx, float partialTicks, int mouseX, int mouseY) protected void renderBg(MatrixStack mx, float partialTicks, int mouseX, int mouseY)
{ {
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
getMinecraft().getTextureManager().bindTexture(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/factory_dropper_gui.png")); getMinecraft().getTextureManager().bind(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/factory_dropper_gui.png"));
final int x0=getGuiLeft(), y0=getGuiTop(), w=getXSize(), h=getYSize(); final int x0=getGuiLeft(), y0=getGuiTop(), w=getXSize(), h=getYSize();
blit(mx, x0, y0, 0, 0, w, h); blit(mx, x0, y0, 0, 0, w, h);
DropperContainer container = (DropperContainer)getContainer(); DropperUiContainer container = (DropperUiContainer)getMenu();
// active drop slot // active drop slot
{ {
int drop_slot_index = container.field(15); int drop_slot_index = container.field(15);

View file

@ -13,6 +13,7 @@ import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.Blocks; import net.minecraft.block.Blocks;
@ -63,6 +64,7 @@ import javax.annotation.Nullable;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
public class EdElectricalFurnace public class EdElectricalFurnace
{ {
public static void on_config(int speed_percent, int standard_energy_per_tick, boolean with_automatic_inventory_pulling) public static void on_config(int speed_percent, int standard_energy_per_tick, boolean with_automatic_inventory_pulling)
@ -74,7 +76,7 @@ public class EdElectricalFurnace
public static class ElectricalFurnaceBlock extends EdFurnace.FurnaceBlock implements IDecorBlock public static class ElectricalFurnaceBlock extends EdFurnace.FurnaceBlock implements IDecorBlock
{ {
public ElectricalFurnaceBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABBs) public ElectricalFurnaceBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABBs)
{ super(config, builder, unrotatedAABBs); } { super(config, builder, unrotatedAABBs); }
@Override @Override
@ -83,31 +85,31 @@ public class EdElectricalFurnace
{ return new EdElectricalFurnace.ElectricalFurnaceTileEntity(); } { return new EdElectricalFurnace.ElectricalFurnaceTileEntity(); }
@Override @Override
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof EdElectricalFurnace.ElectricalFurnaceTileEntity)) return ActionResultType.FAIL; if(!(te instanceof EdElectricalFurnace.ElectricalFurnaceTileEntity)) return ActionResultType.FAIL;
if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL; if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL;
NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te); NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te);
player.addStat(Stats.INTERACT_WITH_FURNACE); player.awardStat(Stats.INTERACT_WITH_FURNACE);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
world.setBlockState(pos, state.with(LIT, false)); world.setBlockAndUpdate(pos, state.setValue(LIT, false));
if(world.isRemote) return; if(world.isClientSide) return;
if((!stack.hasTag()) || (!stack.getTag().contains("inventory"))) return; if((!stack.hasTag()) || (!stack.getTag().contains("inventory"))) return;
CompoundNBT inventory_nbt = stack.getTag().getCompound("inventory"); CompoundNBT inventory_nbt = stack.getTag().getCompound("inventory");
if(inventory_nbt.isEmpty()) return; if(inventory_nbt.isEmpty()) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof EdElectricalFurnace.ElectricalFurnaceTileEntity)) return; if(!(te instanceof EdElectricalFurnace.ElectricalFurnaceTileEntity)) return;
ElectricalFurnaceTileEntity bte = (EdElectricalFurnace.ElectricalFurnaceTileEntity)te; ElectricalFurnaceTileEntity bte = (EdElectricalFurnace.ElectricalFurnaceTileEntity)te;
bte.readnbt(inventory_nbt); bte.readnbt(inventory_nbt);
bte.markDirty(); bte.setChanged();
world.setBlockState(pos, state.with(LIT, bte.burning())); world.setBlockAndUpdate(pos, state.setValue(LIT, bte.burning()));
} }
@Override @Override
@ -150,7 +152,7 @@ public class EdElectricalFurnace
private static int energy_consumption_ = DEFAULT_SCALED_ENERGY_CONSUMPTION; private static int energy_consumption_ = DEFAULT_SCALED_ENERGY_CONSUMPTION;
private static int transfer_energy_consumption_ = DEFAULT_SCALED_ENERGY_CONSUMPTION / 8; private static int transfer_energy_consumption_ = DEFAULT_SCALED_ENERGY_CONSUMPTION / 8;
private static int proc_speed_percent_ = DEFAULT_SPEED_PERCENT; private static int proc_speed_percent_ = DEFAULT_SPEED_PERCENT;
private static double speed_setting_factor_[] = {0.0, 1.0, 1.5, 2.0}; private static final double speed_setting_factor_[] = {0.0, 1.0, 1.5, 2.0};
public static void on_config(int speed_percent, int standard_energy_per_tick, boolean with_automatic_inventory_pulling) public static void on_config(int speed_percent, int standard_energy_per_tick, boolean with_automatic_inventory_pulling)
{ {
@ -198,7 +200,7 @@ public class EdElectricalFurnace
public void reset() public void reset()
{ {
inventory_.clear(); inventory_.clearContent();
burntime_left_ = 0; burntime_left_ = 0;
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
proc_time_needed_ = 0; proc_time_needed_ = 0;
@ -216,7 +218,7 @@ public class EdElectricalFurnace
proc_time_needed_ = nbt.getInt("CookTimeTotal"); proc_time_needed_ = nbt.getInt("CookTimeTotal");
xp_stored_ = nbt.getFloat("XpStored"); xp_stored_ = nbt.getFloat("XpStored");
speed_ = nbt.getInt("SpeedSetting"); speed_ = nbt.getInt("SpeedSetting");
speed_ = (speed_ < 0) ? (1) : ((speed_>MAX_SPEED_SETTING) ? MAX_SPEED_SETTING : speed_); speed_ = (speed_ < 0) ? (1) : (Math.min(speed_, MAX_SPEED_SETTING));
battery_.load(nbt, "Energy"); battery_.load(nbt, "Energy");
inventory_.load(nbt); inventory_.load(nbt);
} }
@ -235,26 +237,26 @@ public class EdElectricalFurnace
public int getComparatorOutput() public int getComparatorOutput()
{ {
return (battery_.isEmpty()) ? (0) : ( return (battery_.isEmpty()) ? (0) : (
(inventory_.getStackInSlot(FIFO_INPUT_1_SLOT_NO).isEmpty() ? 0 : 5) + (inventory_.getItem(FIFO_INPUT_1_SLOT_NO).isEmpty() ? 0 : 5) +
(inventory_.getStackInSlot(FIFO_INPUT_0_SLOT_NO).isEmpty() ? 0 : 5) + (inventory_.getItem(FIFO_INPUT_0_SLOT_NO).isEmpty() ? 0 : 5) +
(inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO).isEmpty() ? 0 : 5) (inventory_.getItem(SMELTING_INPUT_SLOT_NO).isEmpty() ? 0 : 5)
); );
} }
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt); return nbt; } { super.save(nbt); writenbt(nbt); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
item_handler_.invalidate(); item_handler_.invalidate();
energy_handler_.invalidate(); energy_handler_.invalidate();
} }
@ -263,13 +265,13 @@ public class EdElectricalFurnace
@Override @Override
public ITextComponent getName() public ITextComponent getName()
{ final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getTranslationKey() : "Small electrical furnace"); } { final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getDescriptionId() : "Small electrical furnace"); }
// IContainerProvider ---------------------------------------------------------------------- // IContainerProvider ----------------------------------------------------------------------
@Override @Override
public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player ) public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player )
{ return new EdElectricalFurnace.ElectricalFurnaceContainer(id, inventory, inventory_, IWorldPosCallable.of(world, pos), fields); } { return new EdElectricalFurnace.ElectricalFurnaceContainer(id, inventory, inventory_, IWorldPosCallable.create(level, worldPosition), fields); }
// Fields ----------------------------------------------------------------------------------------------- // Fields -----------------------------------------------------------------------------------------------
@ -323,11 +325,11 @@ public class EdElectricalFurnace
{ {
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
if(!(world.getBlockState(pos).getBlock() instanceof ElectricalFurnaceBlock)) return; if(!(level.getBlockState(worldPosition).getBlock() instanceof ElectricalFurnaceBlock)) return;
final boolean was_burning = burning(); final boolean was_burning = burning();
if(was_burning) burntime_left_ -= TICK_INTERVAL; if(was_burning) burntime_left_ -= TICK_INTERVAL;
if(burntime_left_ < 0) burntime_left_ = 0; if(burntime_left_ < 0) burntime_left_ = 0;
if(world.isRemote()) return; if(level.isClientSide()) return;
int battery_energy = battery_.getEnergyStored(); int battery_energy = battery_.getEnergyStored();
boolean update_blockstate = (was_burning != burning()); boolean update_blockstate = (was_burning != burning());
boolean dirty = update_blockstate; boolean dirty = update_blockstate;
@ -345,15 +347,15 @@ public class EdElectricalFurnace
} else if(battery_.getEnergyStored() >= (MAX_ENERGY_BUFFER/2)) { } else if(battery_.getEnergyStored() >= (MAX_ENERGY_BUFFER/2)) {
enabled_ = true; enabled_ = true;
} }
if((!(inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)).isEmpty()) && (enabled_) && (speed_>0)) { if((!(inventory_.getItem(SMELTING_INPUT_SLOT_NO)).isEmpty()) && (enabled_) && (speed_>0)) {
IRecipe last_recipe = currentRecipe(); IRecipe<?> last_recipe = currentRecipe();
updateCurrentRecipe(); updateCurrentRecipe();
if(currentRecipe() != last_recipe) { if(currentRecipe() != last_recipe) {
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
proc_time_needed_ = getSmeltingTimeNeeded(world, inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)); proc_time_needed_ = getSmeltingTimeNeeded(level, inventory_.getItem(SMELTING_INPUT_SLOT_NO));
} }
final boolean can_smelt = canSmeltCurrentItem(); final boolean can_smelt = canSmeltCurrentItem();
if((!can_smelt) && (getSmeltingResult(inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)).isEmpty())) { if((!can_smelt) && (getSmeltingResult(inventory_.getItem(SMELTING_INPUT_SLOT_NO)).isEmpty())) {
// bypass // bypass
if(transferItems(SMELTING_INPUT_SLOT_NO, SMELTING_OUTPUT_SLOT_NO, 1)) dirty = true; if(transferItems(SMELTING_INPUT_SLOT_NO, SMELTING_OUTPUT_SLOT_NO, 1)) dirty = true;
} else { } else {
@ -367,7 +369,7 @@ public class EdElectricalFurnace
proc_time_elapsed_ += (int)(TICK_INTERVAL * proc_speed_percent_ * speed_setting_factor_[speed] / 100); proc_time_elapsed_ += (int)(TICK_INTERVAL * proc_speed_percent_ * speed_setting_factor_[speed] / 100);
if(proc_time_elapsed_ >= proc_time_needed_) { if(proc_time_elapsed_ >= proc_time_needed_) {
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
proc_time_needed_ = getSmeltingTimeNeeded(world, inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)); proc_time_needed_ = getSmeltingTimeNeeded(level, inventory_.getItem(SMELTING_INPUT_SLOT_NO));
smeltCurrentItem(); smeltCurrentItem();
dirty = true; dirty = true;
shift_out = true; shift_out = true;
@ -377,7 +379,7 @@ public class EdElectricalFurnace
} }
} }
} else if(proc_time_elapsed_ > 0) { } else if(proc_time_elapsed_ > 0) {
proc_time_elapsed_ -= ((inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)).isEmpty() ? 20 : 1); proc_time_elapsed_ -= ((inventory_.getItem(SMELTING_INPUT_SLOT_NO)).isEmpty() ? 20 : 1);
if(proc_time_elapsed_ < 0) { proc_time_elapsed_ = 0; shift_out = true; update_blockstate = true; } if(proc_time_elapsed_ < 0) { proc_time_elapsed_ = 0; shift_out = true; update_blockstate = true; }
} }
if(update_blockstate) { if(update_blockstate) {
@ -394,7 +396,7 @@ public class EdElectricalFurnace
power_consumption_accumulator_ = 0; power_consumption_accumulator_ = 0;
power_consumption_timer_ = 0; power_consumption_timer_ = 0;
} }
if(dirty) markDirty(); if(dirty) setChanged();
} }
// Furnace -------------------------------------------------------------------------------------- // Furnace --------------------------------------------------------------------------------------
@ -404,14 +406,14 @@ public class EdElectricalFurnace
private boolean transferItems(final int index_from, final int index_to, int count) private boolean transferItems(final int index_from, final int index_to, int count)
{ {
ItemStack from = inventory_.getStackInSlot(index_from); ItemStack from = inventory_.getItem(index_from);
if(from.isEmpty()) return false; if(from.isEmpty()) return false;
ItemStack to = inventory_.getStackInSlot(index_to); ItemStack to = inventory_.getItem(index_to);
if(from.getCount() < count) count = from.getCount(); if(from.getCount() < count) count = from.getCount();
if(count <= 0) return false; if(count <= 0) return false;
boolean changed = true; boolean changed = true;
if(to.isEmpty()) { if(to.isEmpty()) {
inventory_.setInventorySlotContents(index_to, from.split(count)); inventory_.setItem(index_to, from.split(count));
} else if(to.getCount() >= to.getMaxStackSize()) { } else if(to.getCount() >= to.getMaxStackSize()) {
changed = false; changed = false;
} else if(Inventories.areItemStacksDifferent(from, to)) { } else if(Inventories.areItemStacksDifferent(from, to)) {
@ -426,7 +428,7 @@ public class EdElectricalFurnace
} }
} }
if(from.isEmpty() && from!=ItemStack.EMPTY) { if(from.isEmpty() && from!=ItemStack.EMPTY) {
inventory_.setInventorySlotContents(index_from, ItemStack.EMPTY); inventory_.setItem(index_from, ItemStack.EMPTY);
changed = true; changed = true;
} }
return changed; return changed;
@ -436,28 +438,28 @@ public class EdElectricalFurnace
{ {
boolean dirty = false; boolean dirty = false;
if(battery_.getEnergyStored() < transfer_energy_consumption_) return false; if(battery_.getEnergyStored() < transfer_energy_consumption_) return false;
final BlockState state = world.getBlockState(pos); final BlockState state = level.getBlockState(worldPosition);
if(!(state.getBlock() instanceof ElectricalFurnaceBlock)) return false; if(!(state.getBlock() instanceof ElectricalFurnaceBlock)) return false;
final Direction out_facing = state.get(ElectricalFurnaceBlock.HORIZONTAL_FACING); final Direction out_facing = state.getValue(ElectricalFurnaceBlock.HORIZONTAL_FACING);
if(out && (!inventory_.getStackInSlot(FIFO_OUTPUT_1_SLOT_NO).isEmpty())) { if(out && (!inventory_.getItem(FIFO_OUTPUT_1_SLOT_NO).isEmpty())) {
TileEntity te = world.getTileEntity(pos.offset(out_facing)); TileEntity te = level.getBlockEntity(worldPosition.relative(out_facing));
if(te!=null) { if(te!=null) {
IItemHandler hnd = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, out_facing).orElse(null); IItemHandler hnd = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, out_facing).orElse(null);
if(hnd != null) { if(hnd != null) {
ItemStack remaining = ItemHandlerHelper.insertItemStacked(hnd, inventory_.getStackInSlot(FIFO_OUTPUT_1_SLOT_NO).copy(), false); ItemStack remaining = ItemHandlerHelper.insertItemStacked(hnd, inventory_.getItem(FIFO_OUTPUT_1_SLOT_NO).copy(), false);
inventory_.setInventorySlotContents(FIFO_OUTPUT_1_SLOT_NO, remaining); inventory_.setItem(FIFO_OUTPUT_1_SLOT_NO, remaining);
battery_.draw(transfer_energy_consumption_); battery_.draw(transfer_energy_consumption_);
dirty = true; dirty = true;
} }
} }
} }
if(with_automatic_inventory_pulling_ || is_accepted_hopper(inventory_.getStackInSlot(SMELTING_AUX_SLOT_NO))) { if(with_automatic_inventory_pulling_ || is_accepted_hopper(inventory_.getItem(SMELTING_AUX_SLOT_NO))) {
final Direction inp_facing = state.get(ElectricalFurnaceBlock.HORIZONTAL_FACING).getOpposite(); final Direction inp_facing = state.getValue(ElectricalFurnaceBlock.HORIZONTAL_FACING).getOpposite();
if(inp && (inventory_.getStackInSlot(FIFO_INPUT_1_SLOT_NO).isEmpty()) && (battery_.getEnergyStored() >= transfer_energy_consumption_)) { if(inp && (inventory_.getItem(FIFO_INPUT_1_SLOT_NO).isEmpty()) && (battery_.getEnergyStored() >= transfer_energy_consumption_)) {
final int max_count = MathHelper.clamp((transfer_energy_consumption_ <= 0) ? (64) : (battery_.getEnergyStored()/transfer_energy_consumption_), 1, 64); final int max_count = MathHelper.clamp((transfer_energy_consumption_ <= 0) ? (64) : (battery_.getEnergyStored()/transfer_energy_consumption_), 1, 64);
final ItemStack retrieved = Inventories.extract(Inventories.itemhandler(world, pos.offset(inp_facing), inp_facing), null, max_count, false); final ItemStack retrieved = Inventories.extract(Inventories.itemhandler(level, worldPosition.relative(inp_facing), inp_facing), null, max_count, false);
if(!retrieved.isEmpty()) { if(!retrieved.isEmpty()) {
inventory_.setInventorySlotContents(FIFO_INPUT_1_SLOT_NO, retrieved); inventory_.setItem(FIFO_INPUT_1_SLOT_NO, retrieved);
battery_.draw(max_count * transfer_energy_consumption_); battery_.draw(max_count * transfer_energy_consumption_);
dirty = true; dirty = true;
} }
@ -490,9 +492,9 @@ public class EdElectricalFurnace
private void sync_blockstate() private void sync_blockstate()
{ {
final BlockState state = world.getBlockState(pos); final BlockState state = level.getBlockState(worldPosition);
if((state.getBlock() instanceof ElectricalFurnaceBlock) && (state.get(ElectricalFurnaceBlock.LIT) != burning())) { if((state.getBlock() instanceof ElectricalFurnaceBlock) && (state.getValue(ElectricalFurnaceBlock.LIT) != burning())) {
world.setBlockState(pos, state.with(ElectricalFurnaceBlock.LIT, burning()), 2); level.setBlock(worldPosition, state.setValue(ElectricalFurnaceBlock.LIT, burning()), 2);
} }
} }
@ -514,10 +516,10 @@ public class EdElectricalFurnace
public int field(int index) { return fields_.get(index); } public int field(int index) { return fields_.get(index); }
public PlayerEntity player() { return player_ ; } public PlayerEntity player() { return player_ ; }
public IInventory inventory() { return inventory_ ; } public IInventory inventory() { return inventory_ ; }
public World world() { return player_.world; } public World world() { return player_.level; }
public ElectricalFurnaceContainer(int cid, PlayerInventory player_inventory) public ElectricalFurnaceContainer(int cid, PlayerInventory player_inventory)
{ this(cid, player_inventory, new Inventory(ElectricalFurnaceTileEntity.NUM_OF_SLOTS), IWorldPosCallable.DUMMY, new IntArray(ElectricalFurnaceTileEntity.NUM_OF_FIELDS)); } { this(cid, player_inventory, new Inventory(ElectricalFurnaceTileEntity.NUM_OF_SLOTS), IWorldPosCallable.NULL, new IntArray(ElectricalFurnaceTileEntity.NUM_OF_FIELDS)); }
private ElectricalFurnaceContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields) private ElectricalFurnaceContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields)
{ {
@ -542,42 +544,42 @@ public class EdElectricalFurnace
addSlot(new Slot(player_inventory, x+y*9+9, 8+x*18, 86+y*18)); // player slots: 9..35 addSlot(new Slot(player_inventory, x+y*9+9, 8+x*18, 86+y*18)); // player slots: 9..35
} }
} }
this.trackIntArray(fields_); // === Add reference holders this.addDataSlots(fields_); // === Add reference holders
} }
@Override @Override
public boolean canInteractWith(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return inventory_.isUsableByPlayer(player); } { return inventory_.stillValid(player); }
@Override @Override
public ItemStack transferStackInSlot(PlayerEntity player, int index) public ItemStack quickMoveStack(PlayerEntity player, int index)
{ {
Slot slot = getSlot(index); Slot slot = getSlot(index);
if((slot==null) || (!slot.getHasStack())) return ItemStack.EMPTY; if((slot==null) || (!slot.hasItem())) return ItemStack.EMPTY;
ItemStack slot_stack = slot.getStack(); ItemStack slot_stack = slot.getItem();
ItemStack transferred = slot_stack.copy(); ItemStack transferred = slot_stack.copy();
if((index==2) || (index==5) || (index==6)) { if((index==2) || (index==5) || (index==6)) {
// Output slots // Output slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, true)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, true)) return ItemStack.EMPTY;
slot.onSlotChange(slot_stack, transferred); slot.onQuickCraft(slot_stack, transferred);
} else if((index==0) || (index==3) || (index==4)) { } else if((index==0) || (index==3) || (index==4)) {
// Input slots // Input slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if(index==1) { } else if(index==1) {
// Bypass slot // Bypass slot
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) {
// Player inventory // Player inventory
if(ElectricalFurnaceTileEntity.canSmelt(world(), slot_stack)) { if(ElectricalFurnaceTileEntity.canSmelt(world(), slot_stack)) {
if( if(
(!mergeItemStack(slot_stack, 0, 1, false)) && // smelting input (!moveItemStackTo(slot_stack, 0, 1, false)) && // smelting input
(!mergeItemStack(slot_stack, 3, 4, false)) && // fifo0 (!moveItemStackTo(slot_stack, 3, 4, false)) && // fifo0
(!mergeItemStack(slot_stack, 4, 5, false)) // fifo1 (!moveItemStackTo(slot_stack, 4, 5, false)) // fifo1
) return ItemStack.EMPTY; ) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index < PLAYER_INV_START_SLOTNO+27)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index < PLAYER_INV_START_SLOTNO+27)) {
// player inventory --> player hotbar // player inventory --> player hotbar
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO+27, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO+27, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO+27) && (index < PLAYER_INV_START_SLOTNO+36) && (!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+27, false))) { } else if((index >= PLAYER_INV_START_SLOTNO+27) && (index < PLAYER_INV_START_SLOTNO+36) && (!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+27, false))) {
// player hotbar --> player inventory // player hotbar --> player inventory
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
@ -586,9 +588,9 @@ public class EdElectricalFurnace
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
if(slot_stack.isEmpty()) { if(slot_stack.isEmpty()) {
slot.putStack(ItemStack.EMPTY); slot.set(ItemStack.EMPTY);
} else { } else {
slot.onSlotChanged(); slot.setChanged();
} }
if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY; if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY;
slot.onTake(player, slot_stack); slot.onTake(player, slot_stack);
@ -599,11 +601,11 @@ public class EdElectricalFurnace
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(CompoundNBT nbt) public void onGuiAction(CompoundNBT nbt)
{ Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); } { Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt); }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(String key, int value) public void onGuiAction(String key, int value)
{ CompoundNBT nbt=new CompoundNBT(); nbt.putInt(key, value); Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); } { CompoundNBT nbt=new CompoundNBT(); nbt.putInt(key, value); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt); }
@Override @Override
public void onServerPacketReceived(int windowId, CompoundNBT nbt) public void onServerPacketReceived(int windowId, CompoundNBT nbt)
@ -614,7 +616,7 @@ public class EdElectricalFurnace
if(!(inventory_ instanceof StorageInventory)) return; if(!(inventory_ instanceof StorageInventory)) return;
ElectricalFurnaceTileEntity te = (ElectricalFurnaceTileEntity)(((StorageInventory)inventory_).getTileEntity()); ElectricalFurnaceTileEntity te = (ElectricalFurnaceTileEntity)(((StorageInventory)inventory_).getTileEntity());
if(nbt.contains("speed")) te.speed_ = MathHelper.clamp(nbt.getInt("speed"), 0, ElectricalFurnaceTileEntity.MAX_SPEED_SETTING); if(nbt.contains("speed")) te.speed_ = MathHelper.clamp(nbt.getInt("speed"), 0, ElectricalFurnaceTileEntity.MAX_SPEED_SETTING);
te.markDirty(); te.setChanged();
} }
} }
@ -635,15 +637,15 @@ public class EdElectricalFurnace
public void init() public void init()
{ {
super.init(); super.init();
final String prefix = ModContent.SMALL_ELECTRICAL_FURNACE.getTranslationKey() + ".tooltips."; final String prefix = ModContent.SMALL_ELECTRICAL_FURNACE.getDescriptionId() + ".tooltips.";
final int x0 = getGuiLeft(), y0 = getGuiTop(); final int x0 = getGuiLeft(), y0 = getGuiTop();
final Slot aux = container.getSlot(ElectricalFurnaceTileEntity.SMELTING_AUX_SLOT_NO); final Slot aux = menu.getSlot(ElectricalFurnaceTileEntity.SMELTING_AUX_SLOT_NO);
tooltip_.init( tooltip_.init(
new TipRange(x0+135, y0+50, 25, 25, new TranslationTextComponent(prefix + "speed")), new TipRange(x0+135, y0+50, 25, 25, new TranslationTextComponent(prefix + "speed")),
new TipRange(x0+aux.xPos, y0+aux.yPos, 16, 16, new TranslationTextComponent(prefix + "auxslot")), new TipRange(x0+aux.x, y0+aux.y, 16, 16, new TranslationTextComponent(prefix + "auxslot")),
new TipRange(x0+80, y0+55, 50, 14, ()->{ new TipRange(x0+80, y0+55, 50, 14, ()->{
final int soc = getContainer().field(1) * 100 / Math.max(getContainer().field(5), 1); final int soc = getMenu().field(1) * 100 / Math.max(getMenu().field(5), 1);
final int consumption = getContainer().field(7); final int consumption = getMenu().field(7);
return new TranslationTextComponent(prefix + "capacitors", soc, consumption); return new TranslationTextComponent(prefix + "capacitors", soc, consumption);
}) })
); );
@ -654,23 +656,23 @@ public class EdElectricalFurnace
{ {
renderBackground(mx); renderBackground(mx);
super.render(mx, mouseX, mouseY, partialTicks); super.render(mx, mouseX, mouseY, partialTicks);
if(!tooltip_.render(mx, this, mouseX, mouseY)) renderHoveredTooltip(mx, mouseX, mouseY); if(!tooltip_.render(mx, this, mouseX, mouseY)) renderTooltip(mx, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerForegroundLayer(MatrixStack mx, int x, int y) protected void renderLabels(MatrixStack mx, int x, int y)
{} {}
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void drawGuiContainerBackgroundLayer(MatrixStack mx, float partialTicks, int mouseX, int mouseY) protected void renderBg(MatrixStack mx, float partialTicks, int mouseX, int mouseY)
{ {
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
getMinecraft().getTextureManager().bindTexture(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/small_electrical_furnace_gui.png")); getMinecraft().getTextureManager().bind(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/small_electrical_furnace_gui.png"));
final int x0=guiLeft, y0=guiTop, w=xSize, h=ySize; final int x0=leftPos, y0=topPos, w=imageWidth, h=imageHeight;
blit(mx, x0, y0, 0, 0, w, h); blit(mx, x0, y0, 0, 0, w, h);
if(getContainer().field(6)!=0) { if(getMenu().field(6)!=0) {
final int hi = 13; final int hi = 13;
final int k = heat_px(hi); final int k = heat_px(hi);
blit(mx, x0+62, y0+55+hi-k, 177, hi-k, 13, k); blit(mx, x0+62, y0+55+hi-k, 177, hi-k, 13, k);
@ -678,7 +680,7 @@ public class EdElectricalFurnace
blit(mx, x0+79, y0+30, 176, 15, 1+progress_px(17), 15); blit(mx, x0+79, y0+30, 176, 15, 1+progress_px(17), 15);
int we = energy_px(32, 8); int we = energy_px(32, 8);
if(we>0) blit(mx, x0+90, y0+54, 185, 30, we, 13); if(we>0) blit(mx, x0+90, y0+54, 185, 30, we, 13);
switch(getContainer().field(4)) { switch(getMenu().field(4)) {
case 0: blit(mx, x0+144, y0+57, 180, 57, 6, 9); break; case 0: blit(mx, x0+144, y0+57, 180, 57, 6, 9); break;
case 1: blit(mx, x0+142, y0+58, 190, 58, 9, 6); break; case 1: blit(mx, x0+142, y0+58, 190, 58, 9, 6); break;
case 2: blit(mx, x0+144, y0+56, 200, 57, 6, 9); break; case 2: blit(mx, x0+144, y0+56, 200, 57, 6, 9); break;
@ -692,35 +694,35 @@ public class EdElectricalFurnace
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) public boolean mouseClicked(double mouseX, double mouseY, int mouseButton)
{ {
tooltip_.resetTimer(); tooltip_.resetTimer();
ElectricalFurnaceContainer container = (ElectricalFurnaceContainer)getContainer(); ElectricalFurnaceContainer container = (ElectricalFurnaceContainer)getMenu();
int mx = (int)(mouseX - getGuiLeft() + .5), my = (int)(mouseY - getGuiTop() + .5); int mx = (int)(mouseX - getGuiLeft() + .5), my = (int)(mouseY - getGuiTop() + .5);
if((!isPointInRegion(136, 48, 28, 28, mouseX, mouseY))) { if((!isHovering(136, 48, 28, 28, mouseX, mouseY))) {
return super.mouseClicked(mouseX, mouseY, mouseButton); return super.mouseClicked(mouseX, mouseY, mouseButton);
} else if(isPointInRegion(144, 64, 6, 10, mouseX, mouseY)) { } else if(isHovering(144, 64, 6, 10, mouseX, mouseY)) {
container.onGuiAction("speed", 0); container.onGuiAction("speed", 0);
} else if(isPointInRegion(134, 58, 10, 6, mouseX, mouseY)) { } else if(isHovering(134, 58, 10, 6, mouseX, mouseY)) {
container.onGuiAction("speed", 1); container.onGuiAction("speed", 1);
} else if(isPointInRegion(144, 48, 6, 10, mouseX, mouseY)) { } else if(isHovering(144, 48, 6, 10, mouseX, mouseY)) {
container.onGuiAction("speed", 2); container.onGuiAction("speed", 2);
} else if(isPointInRegion(150, 58, 10, 6, mouseX, mouseY)) { } else if(isHovering(150, 58, 10, 6, mouseX, mouseY)) {
container.onGuiAction("speed", 3); container.onGuiAction("speed", 3);
} }
return true; return true;
} }
private int progress_px(int pixels) private int progress_px(int pixels)
{ final int tc=getContainer().field(2), T=getContainer().field(3); return ((T>0) && (tc>0)) ? (tc * pixels / T) : (0); } { final int tc=getMenu().field(2), T=getMenu().field(3); return ((T>0) && (tc>0)) ? (tc * pixels / T) : (0); }
private int heat_px(int pixels) private int heat_px(int pixels)
{ {
int k = ((getContainer().field(0) * (pixels+1)) / (EdElectricalFurnace.ElectricalFurnaceTileEntity.HEAT_CAPACITY)); int k = ((getMenu().field(0) * (pixels+1)) / (EdElectricalFurnace.ElectricalFurnaceTileEntity.HEAT_CAPACITY));
return (k < pixels) ? k : pixels; return Math.min(k, pixels);
} }
private int energy_px(int maxwidth, int quantization) private int energy_px(int maxwidth, int quantization)
{ {
int emax = getContainer().field(5); int emax = getMenu().field(5);
int k = ((maxwidth * getContainer().field(1) * 9) / 8) / ((emax>0?emax:1)+1); int k = ((maxwidth * getMenu().field(1) * 9) / 8) / ((emax>0?emax:1)+1);
k = (k >= maxwidth-2) ? maxwidth : k; k = (k >= maxwidth-2) ? maxwidth : k;
if(quantization > 0) k = ((k+(quantization/2))/quantization) * quantization; if(quantization > 0) k = ((k+(quantization/2))/quantization) * quantization;
return k; return k;

View file

@ -17,10 +17,10 @@ import net.minecraft.block.*;
public class EdFenceBlock extends StandardFenceBlock implements IDecorBlock public class EdFenceBlock extends StandardFenceBlock implements IDecorBlock
{ {
public EdFenceBlock(long config, Block.Properties properties) public EdFenceBlock(long config, AbstractBlock.Properties properties)
{ super(config, properties); } { super(config, properties); }
public EdFenceBlock(long config, Block.Properties properties, double pole_width, double pole_height, double side_width, double side_min_y, double side_max_low_y, double side_max_tall_y) public EdFenceBlock(long config, AbstractBlock.Properties properties, double pole_width, double pole_height, double side_width, double side_min_y, double side_max_low_y, double side_max_tall_y)
{ super(config, properties, pole_width, pole_height, side_width, side_min_y, side_max_low_y, side_max_tall_y); } { super(config, properties, pole_width, pole_height, side_width, side_min_y, side_max_low_y, side_max_tall_y); }
@Override @Override

View file

@ -8,7 +8,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.Block; import net.minecraft.block.AbstractBlock;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntitySpawnPlacementRegistry; import net.minecraft.entity.EntitySpawnPlacementRegistry;
@ -25,7 +25,7 @@ import javax.annotation.Nullable;
public class EdFloorGratingBlock extends DecorBlock.WaterLoggable implements IDecorBlock public class EdFloorGratingBlock extends DecorBlock.WaterLoggable implements IDecorBlock
{ {
public EdFloorGratingBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB) public EdFloorGratingBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
@ -42,30 +42,30 @@ public class EdFloorGratingBlock extends DecorBlock.WaterLoggable implements IDe
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void onEntityCollision(BlockState state, World world, BlockPos pos, Entity entity) public void entityInside(BlockState state, World world, BlockPos pos, Entity entity)
{ {
if(!(entity instanceof ItemEntity)) return; if(!(entity instanceof ItemEntity)) return;
final boolean colliding = ((entity.getPositionVec().y-pos.getY()) > 0.7); final boolean colliding = ((entity.position().y-pos.getY()) > 0.7);
if(colliding || (entity.getMotion().getY() > 0)) { if(colliding || (entity.getDeltaMovement().y() > 0)) {
double x = pos.getX() + 0.5; double x = pos.getX() + 0.5;
double y = MathHelper.clamp(entity.getPositionVec().y-0.3, pos.getY(), pos.getY()+0.6); double y = MathHelper.clamp(entity.position().y-0.3, pos.getY(), pos.getY()+0.6);
double z = pos.getZ() + 0.5; double z = pos.getZ() + 0.5;
double vx = entity.getMotion().getX(); double vx = entity.getDeltaMovement().x();
double vy = entity.getMotion().getY(); double vy = entity.getDeltaMovement().y();
double vz = entity.getMotion().getZ(); double vz = entity.getDeltaMovement().z();
if(colliding) { if(colliding) {
vx = 0; vx = 0;
vy = -0.3; vy = -0.3;
vz = 0; vz = 0;
if((entity.getPositionVec().y-pos.getY()) > 0.8) y = pos.getY() + 0.6; if((entity.position().y-pos.getY()) > 0.8) y = pos.getY() + 0.6;
entity.prevPosX = x+0.1; entity.xo = x+0.1;
entity.prevPosY = y+0.1; entity.yo = y+0.1;
entity.prevPosZ = z+0.1; entity.zo = z+0.1;
} }
vy = MathHelper.clamp(vy, -0.3, 0); vy = MathHelper.clamp(vy, -0.3, 0);
entity.setMotion(vx, vy, vz); entity.setDeltaMovement(vx, vy, vz);
entity.fallDistance = 0; entity.fallDistance = 0;
entity.setPositionAndUpdate(x,y,z); entity.teleportTo(x,y,z);
} }
} }

View file

@ -22,6 +22,7 @@ import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
@ -57,6 +58,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class EdFluidBarrel public class EdFluidBarrel
{ {
//-------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------
@ -84,10 +86,10 @@ public class EdFluidBarrel
public static final int FILL_LEVEL_MAX = 4; public static final int FILL_LEVEL_MAX = 4;
public static final IntegerProperty FILL_LEVEL = IntegerProperty.create("level", 0, FILL_LEVEL_MAX); public static final IntegerProperty FILL_LEVEL = IntegerProperty.create("level", 0, FILL_LEVEL_MAX);
public FluidBarrelBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABB) public FluidBarrelBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABB)
{ {
super(config, builder, unrotatedAABB); super(config, builder, unrotatedAABB);
setDefaultState(super.getDefaultState().with(FACING, Direction.UP).with(FILL_LEVEL, 0)); registerDefaultState(super.defaultBlockState().setValue(FACING, Direction.UP).setValue(FILL_LEVEL, 0));
} }
// IBlockItemFactory ---------------------------------------------------------------------------- // IBlockItemFactory ----------------------------------------------------------------------------
@ -106,7 +108,7 @@ public class EdFluidBarrel
public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof FluidBarrelTileEntity)) return stacks; if(!(te instanceof FluidBarrelTileEntity)) return stacks;
ItemStack stack = new ItemStack(this, 1); ItemStack stack = new ItemStack(this, 1);
CompoundNBT te_nbt = ((FluidBarrelTileEntity) te).clear_getnbt(); CompoundNBT te_nbt = ((FluidBarrelTileEntity) te).clear_getnbt();
@ -123,29 +125,29 @@ public class EdFluidBarrel
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(final ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(final ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ {
if( if(
(!(stack.getItem() instanceof FluidBarrelItem)) || (!(stack.getItem() instanceof FluidBarrelItem)) ||
(Auxiliaries.Tooltip.helpCondition()) (Auxiliaries.Tooltip.helpCondition())
) { ) {
super.addInformation(stack, world, tooltip, flag); return; super.appendHoverText(stack, world, tooltip, flag); return;
} }
FluidStack fs = FluidBarrelItem.getFluid(stack); FluidStack fs = FluidBarrelItem.getFluid(stack);
if(!fs.isEmpty()) { if(!fs.isEmpty()) {
tooltip.add(Auxiliaries.localizable(getTranslationKey()+".status.tip", new Object[] { tooltip.add(Auxiliaries.localizable(getDescriptionId()+".status.tip", new Object[] {
Integer.toString(fs.getAmount()), Integer.toString(fs.getAmount()),
Integer.toString(capacity_), Integer.toString(capacity_),
new TranslationTextComponent(fs.getTranslationKey()) new TranslationTextComponent(fs.getTranslationKey())
})); }));
} else { } else {
tooltip.add(Auxiliaries.localizable(getTranslationKey()+".status.tip.empty", new Object[] { tooltip.add(Auxiliaries.localizable(getDescriptionId()+".status.tip.empty", new Object[] {
"0", "0",
Integer.toString(capacity_), Integer.toString(capacity_),
})); }));
} }
if(!Auxiliaries.Tooltip.extendedTipCondition()) { if(!Auxiliaries.Tooltip.extendedTipCondition()) {
super.addInformation(stack, world, tooltip, flag); super.appendHoverText(stack, world, tooltip, flag);
} }
} }
@ -159,55 +161,55 @@ public class EdFluidBarrel
{ return new EdFluidBarrel.FluidBarrelTileEntity(); } { return new EdFluidBarrel.FluidBarrelTileEntity(); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(FILL_LEVEL); } { super.createBlockStateDefinition(builder); builder.add(FILL_LEVEL); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
BlockState state = super.getStateForPlacement(context); BlockState state = super.getStateForPlacement(context);
if(!context.getPlayer().isSneaking()) state = state.with(FACING, Direction.UP); if(!context.getPlayer().isShiftKeyDown()) state = state.setValue(FACING, Direction.UP);
return state; return state;
} }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
if(world.isRemote) return; if(world.isClientSide) return;
if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return; if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return;
CompoundNBT te_nbt = stack.getTag().getCompound("tedata"); CompoundNBT te_nbt = stack.getTag().getCompound("tedata");
if(te_nbt.isEmpty()) return; if(te_nbt.isEmpty()) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof FluidBarrelTileEntity)) return; if(!(te instanceof FluidBarrelTileEntity)) return;
((FluidBarrelTileEntity)te).readnbt(te_nbt); ((FluidBarrelTileEntity)te).readnbt(te_nbt);
((FluidBarrelTileEntity)te).markDirty(); ((FluidBarrelTileEntity)te).setChanged();
world.getPendingBlockTicks().scheduleTick(pos, this, 4); world.getBlockTicks().scheduleTick(pos, this, 4);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(player.getHeldItem(hand).getItem() == asItem()) return ActionResultType.PASS; // Pass that to block placement. if(player.getItemInHand(hand).getItem() == asItem()) return ActionResultType.PASS; // Pass that to block placement.
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof FluidBarrelTileEntity)) return ActionResultType.FAIL; if(!(te instanceof FluidBarrelTileEntity)) return ActionResultType.FAIL;
if(!((FluidBarrelTileEntity)te).handlePlayerInteraction(state, world, pos, player, hand)) return ActionResultType.PASS; if(!((FluidBarrelTileEntity)te).handlePlayerInteraction(state, world, pos, player, hand)) return ActionResultType.PASS;
world.getPendingBlockTicks().scheduleTick(pos, this, 4); world.getBlockTicks().scheduleTick(pos, this, 4);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState state, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState state, World world, BlockPos pos)
{ {
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof FluidBarrelTileEntity)) return 0; if(!(te instanceof FluidBarrelTileEntity)) return 0;
return (int)MathHelper.clamp(((FluidBarrelTileEntity)te).getNormalizedFillLevel() * 15, 0, 15); return (int)MathHelper.clamp(((FluidBarrelTileEntity)te).getNormalizedFillLevel() * 15, 0, 15);
} }
@ -248,16 +250,16 @@ public class EdFluidBarrel
public boolean handlePlayerInteraction(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand) public boolean handlePlayerInteraction(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand)
{ {
if(world.isRemote()) return false; if(world.isClientSide()) return false;
{ {
Tuple<Fluid,Integer> transferred = Fluidics.manualTrackedFluidHandlerInteraction(world, pos, null, player, hand); Tuple<Fluid,Integer> transferred = Fluidics.manualTrackedFluidHandlerInteraction(world, pos, null, player, hand);
if(transferred==null) { if(transferred==null) {
world.playSound(null, pos, SoundEvents.BLOCK_IRON_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 0.2f, 0.02f); world.playSound(null, pos, SoundEvents.IRON_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 0.2f, 0.02f);
} else if(transferred.getB() > 0) { } else if(transferred.getB() > 0) {
SoundEvent se = (transferred.getA()==Fluids.LAVA) ? SoundEvents.ITEM_BUCKET_EMPTY_LAVA: SoundEvents.ITEM_BUCKET_EMPTY; SoundEvent se = (transferred.getA()==Fluids.LAVA) ? SoundEvents.BUCKET_EMPTY_LAVA: SoundEvents.BUCKET_EMPTY;
world.playSound(null, pos, se, SoundCategory.BLOCKS, 1f, 1f); world.playSound(null, pos, se, SoundCategory.BLOCKS, 1f, 1f);
} else { } else {
SoundEvent se = (transferred.getA()==Fluids.LAVA) ? SoundEvents.ITEM_BUCKET_FILL_LAVA : SoundEvents.ITEM_BUCKET_FILL; SoundEvent se = (transferred.getA()==Fluids.LAVA) ? SoundEvents.BUCKET_FILL_LAVA : SoundEvents.BUCKET_FILL;
world.playSound(null, pos, se, SoundCategory.BLOCKS, 1f, 1f); world.playSound(null, pos, se, SoundCategory.BLOCKS, 1f, 1f);
} }
} }
@ -287,16 +289,16 @@ public class EdFluidBarrel
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); return writenbt(nbt); } { super.save(nbt); return writenbt(nbt); }
@Override @Override
public void remove() public void setRemoved()
{ super.remove(); fluid_handler_.invalidate(); } { super.setRemoved(); fluid_handler_.invalidate(); }
public CompoundNBT clear_getnbt() public CompoundNBT clear_getnbt()
{ return tank_.save(new CompoundNBT()); } { return tank_.save(new CompoundNBT()); }
@ -315,7 +317,7 @@ public class EdFluidBarrel
private boolean transfer_down() private boolean transfer_down()
{ {
if(tank_.isEmpty()) return false; if(tank_.isEmpty()) return false;
final IFluidHandler fh = FluidUtil.getFluidHandler(world, pos.down(), Direction.UP).orElse(null); final IFluidHandler fh = FluidUtil.getFluidHandler(level, worldPosition.below(), Direction.UP).orElse(null);
if(fh==null) return false; if(fh==null) return false;
final FluidStack fs = tank_.getFluid().copy(); final FluidStack fs = tank_.getFluid().copy();
if(fs.getAmount() > tile_fluid_handler_transfer_rate_) fs.setAmount(tile_fluid_handler_transfer_rate_); if(fs.getAmount() > tile_fluid_handler_transfer_rate_) fs.setAmount(tile_fluid_handler_transfer_rate_);
@ -327,17 +329,17 @@ public class EdFluidBarrel
public void tick() public void tick()
{ {
if((world.isRemote()) || (--tick_timer_>=0)) return; if((level.isClientSide()) || (--tick_timer_>=0)) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
final BlockState state = getBlockState(); final BlockState state = getBlockState();
final Block block = state.getBlock(); final Block block = state.getBlock();
if(!(block instanceof FluidBarrelBlock)) return; if(!(block instanceof FluidBarrelBlock)) return;
if(state.get(FluidBarrelBlock.FACING).getAxis().isVertical()) transfer_down(); // tick_timer_ ==> 1 if something was transferred, otherwise no need to waste CPU if(state.getValue(FluidBarrelBlock.FACING).getAxis().isVertical()) transfer_down(); // tick_timer_ ==> 1 if something was transferred, otherwise no need to waste CPU
double norm_level = getNormalizedFillLevel(); double norm_level = getNormalizedFillLevel();
int fill_level = (norm_level <= 0) ? 0 : ((int)MathHelper.clamp((norm_level * FluidBarrelBlock.FILL_LEVEL_MAX)+0.5, 1, FluidBarrelBlock.FILL_LEVEL_MAX)); int fill_level = (norm_level <= 0) ? 0 : ((int)MathHelper.clamp((norm_level * FluidBarrelBlock.FILL_LEVEL_MAX)+0.5, 1, FluidBarrelBlock.FILL_LEVEL_MAX));
if(fill_level != state.get(FluidBarrelBlock.FILL_LEVEL)) { if(fill_level != state.getValue(FluidBarrelBlock.FILL_LEVEL)) {
world.setBlockState(pos, state.with(FluidBarrelBlock.FILL_LEVEL, fill_level), 2); level.setBlock(worldPosition, state.setValue(FluidBarrelBlock.FILL_LEVEL, fill_level), 2);
world.notifyNeighborsOfStateChange(pos, block); level.updateNeighborsAt(worldPosition, block);
} }
} }

View file

@ -67,7 +67,7 @@ public class EdFluidFunnel
public static final int FILL_LEVEL_MAX = 3; public static final int FILL_LEVEL_MAX = 3;
public static final IntegerProperty FILL_LEVEL = IntegerProperty.create("level", 0, FILL_LEVEL_MAX); public static final IntegerProperty FILL_LEVEL = IntegerProperty.create("level", 0, FILL_LEVEL_MAX);
public FluidFunnelBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABB) public FluidFunnelBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
@ -75,13 +75,13 @@ public class EdFluidFunnel
{ return RenderTypeHint.CUTOUT; } { return RenderTypeHint.CUTOUT; }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(FILL_LEVEL); } { super.createBlockStateDefinition(builder); builder.add(FILL_LEVEL); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(FILL_LEVEL, 0); } { return super.getStateForPlacement(context).setValue(FILL_LEVEL, 0); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -94,26 +94,26 @@ public class EdFluidFunnel
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState state, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState state, World world, BlockPos pos)
{ return MathHelper.clamp((state.get(FILL_LEVEL)*5), 0, 15); } { return MathHelper.clamp((state.getValue(FILL_LEVEL)*5), 0, 15); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
if(world.isRemote) return; if(world.isClientSide) return;
if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return; if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return;
CompoundNBT te_nbt = stack.getTag().getCompound("tedata"); CompoundNBT te_nbt = stack.getTag().getCompound("tedata");
if(te_nbt.isEmpty()) return; if(te_nbt.isEmpty()) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof FluidFunnelTileEntity)) return; if(!(te instanceof FluidFunnelTileEntity)) return;
((FluidFunnelTileEntity)te).readnbt(te_nbt); ((FluidFunnelTileEntity)te).readnbt(te_nbt);
((FluidFunnelTileEntity)te).markDirty(); ((FluidFunnelTileEntity)te).setChanged();
world.setBlockState(pos, state.with(FILL_LEVEL, 0)); world.setBlockAndUpdate(pos, state.setValue(FILL_LEVEL, 0));
} }
@Override @Override
@ -124,7 +124,7 @@ public class EdFluidFunnel
public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof FluidFunnelTileEntity)) return stacks; if(!(te instanceof FluidFunnelTileEntity)) return stacks;
if(!explosion) { if(!explosion) {
ItemStack stack = new ItemStack(this, 1); ItemStack stack = new ItemStack(this, 1);
@ -144,18 +144,18 @@ public class EdFluidFunnel
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote) return ActionResultType.SUCCESS; if(world.isClientSide) return ActionResultType.SUCCESS;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof FluidFunnelTileEntity)) return ActionResultType.FAIL; if(!(te instanceof FluidFunnelTileEntity)) return ActionResultType.FAIL;
return FluidUtil.interactWithFluidHandler(player, hand, world, pos, rayTraceResult.getFace()) ? ActionResultType.CONSUME : ActionResultType.FAIL; return FluidUtil.interactWithFluidHandler(player, hand, world, pos, rayTraceResult.getDirection()) ? ActionResultType.CONSUME : ActionResultType.FAIL;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused)
{ TileEntity te = world.getTileEntity(pos); if(te instanceof FluidFunnelTileEntity) ((FluidFunnelTileEntity)te).block_changed(); } { TileEntity te = world.getBlockEntity(pos); if(te instanceof FluidFunnelTileEntity) ((FluidFunnelTileEntity)te).block_changed(); }
@Override @Override
public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side) public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
@ -212,17 +212,17 @@ public class EdFluidFunnel
// TileEntity ----------------------------------------------------------------------------------------- // TileEntity -----------------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt); return nbt; } { super.save(nbt); writenbt(nbt); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
fluid_handler_.invalidate(); fluid_handler_.invalidate();
} }
@ -239,29 +239,29 @@ public class EdFluidFunnel
private FluidState get_fluidstate(BlockPos pos) private FluidState get_fluidstate(BlockPos pos)
{ {
final Block collection_block = world.getBlockState(pos).getBlock(); final Block collection_block = level.getBlockState(pos).getBlock();
if((!(collection_block instanceof IFluidBlock)) && (!(collection_block instanceof FlowingFluidBlock)) && (!(collection_block instanceof IWaterLoggable))) { if((!(collection_block instanceof IFluidBlock)) && (!(collection_block instanceof FlowingFluidBlock)) && (!(collection_block instanceof IWaterLoggable))) {
return Fluids.EMPTY.getDefaultState(); return Fluids.EMPTY.defaultFluidState();
} }
return world.getFluidState(pos); return level.getFluidState(pos);
} }
private boolean try_pick(BlockPos pos, FluidState fluidstate) private boolean try_pick(BlockPos pos, FluidState fluidstate)
{ {
if(!fluidstate.isSource()) return false; if(!fluidstate.isSource()) return false;
IFluidHandler hnd = FluidUtil.getFluidHandler(world, pos, null).orElse(null); IFluidHandler hnd = FluidUtil.getFluidHandler(level, pos, null).orElse(null);
FluidStack fs; FluidStack fs;
if(hnd != null) { if(hnd != null) {
fs = hnd.drain(TANK_CAPACITY, FluidAction.EXECUTE); // IFluidBlock fs = hnd.drain(TANK_CAPACITY, FluidAction.EXECUTE); // IFluidBlock
} else { } else {
fs = new FluidStack(fluidstate.getFluid(), 1000); fs = new FluidStack(fluidstate.getType(), 1000);
BlockState state = world.getBlockState(pos); BlockState state = level.getBlockState(pos);
if(state instanceof IBucketPickupHandler) { if(state instanceof IBucketPickupHandler) {
((IBucketPickupHandler)state).pickupFluid(world, pos, state); ((IBucketPickupHandler)state).takeLiquid(level, pos, state);
} else if((state.getBlock() instanceof IWaterLoggable) && (state.hasProperty(BlockStateProperties.WATERLOGGED))) { } else if((state.getBlock() instanceof IWaterLoggable) && (state.hasProperty(BlockStateProperties.WATERLOGGED))) {
world.setBlockState(pos, state.with(BlockStateProperties.WATERLOGGED, false), 1|2); level.setBlock(pos, state.setValue(BlockStateProperties.WATERLOGGED, false), 1|2);
} else { } else {
world.setBlockState(pos, Blocks.AIR.getDefaultState(), 1|2); // ok we can't leave the block, that would be an infinite source of an unknown fluid. level.setBlock(pos, Blocks.AIR.defaultBlockState(), 1|2); // ok we can't leave the block, that would be an infinite source of an unknown fluid.
} }
} }
if((fs==null) || (fs.isEmpty())) return false; // it's marked nonnull but I don't trust every modder - including meself ... if((fs==null) || (fs.isEmpty())) return false; // it's marked nonnull but I don't trust every modder - including meself ...
@ -278,10 +278,10 @@ public class EdFluidFunnel
private boolean can_pick(BlockPos pos, FluidState fluidstate) private boolean can_pick(BlockPos pos, FluidState fluidstate)
{ {
if(fluidstate.isSource()) return true; if(fluidstate.isSource()) return true;
IFluidHandler hnd = FluidUtil.getFluidHandler(world, pos, null).orElse(null); IFluidHandler hnd = FluidUtil.getFluidHandler(level, pos, null).orElse(null);
if(hnd == null) return false; if(hnd == null) return false;
FluidStack fs = hnd.drain(TANK_CAPACITY, FluidAction.SIMULATE); // don't trust that everyone returns nonnull FluidStack fs = hnd.drain(TANK_CAPACITY, FluidAction.SIMULATE); // don't trust that everyone returns nonnull
return ((fs!=null) && (!fs.isEmpty())) && (fluidstate.getFluid().isEquivalentTo(fs.getFluid())); return ((fs!=null) && (!fs.isEmpty())) && (fluidstate.getType().isSame(fs.getFluid()));
} }
private void rebuild_search_offsets(boolean intensive) private void rebuild_search_offsets(boolean intensive)
@ -304,10 +304,10 @@ public class EdFluidFunnel
{ {
FluidState collection_fluidstate = get_fluidstate(collection_pos); FluidState collection_fluidstate = get_fluidstate(collection_pos);
if(collection_fluidstate.isEmpty()) return false; if(collection_fluidstate.isEmpty()) return false;
Fluid fluid_to_collect = collection_fluidstate.getFluid(); Fluid fluid_to_collect = collection_fluidstate.getType();
if((!tank_.isEmpty()) && (!tank_.getFluid().getFluid().isEquivalentTo(fluid_to_collect))) return false; if((!tank_.isEmpty()) && (!tank_.getFluid().getFluid().isSame(fluid_to_collect))) return false;
if(try_pick(collection_pos, collection_fluidstate)) { last_pick_pos_ = collection_pos; return true; } // Blocks directly always first. Allows water source blocks to recover/reflow to source blocks. if(try_pick(collection_pos, collection_fluidstate)) { last_pick_pos_ = collection_pos; return true; } // Blocks directly always first. Allows water source blocks to recover/reflow to source blocks.
if((last_pick_pos_==null) || (last_pick_pos_.distanceSq(collection_pos) > MAX_TRACK_RADIUS_SQ)) { last_pick_pos_ = collection_pos; search_offsets_ = null; } if((last_pick_pos_==null) || (last_pick_pos_.distSqr(collection_pos) > MAX_TRACK_RADIUS_SQ)) { last_pick_pos_ = collection_pos; search_offsets_ = null; }
BlockPos pos = last_pick_pos_; BlockPos pos = last_pick_pos_;
HashSet<BlockPos> checked = new HashSet<>(); HashSet<BlockPos> checked = new HashSet<>();
Stack<BlockPos> trail = new Stack<BlockPos>(); Stack<BlockPos> trail = new Stack<BlockPos>();
@ -321,12 +321,12 @@ public class EdFluidFunnel
while(++steps <= max) { while(++steps <= max) {
int num_adjacent = 0; int num_adjacent = 0;
for(int i=0; i<search_offsets_.size(); ++i) { for(int i=0; i<search_offsets_.size(); ++i) {
BlockPos p = pos.add(search_offsets_.get(i)); BlockPos p = pos.offset(search_offsets_.get(i));
if(checked.contains(p)) continue; if(checked.contains(p)) continue;
checked.add(p); checked.add(p);
++steps; ++steps;
FluidState fluidstate = get_fluidstate(p); FluidState fluidstate = get_fluidstate(p);
if(fluidstate.getFluid().isEquivalentTo(fluid_to_collect)) { if(fluidstate.getType().isSame(fluid_to_collect)) {
++num_adjacent; ++num_adjacent;
pos = p; pos = p;
trail.push(pos); trail.push(pos);
@ -334,10 +334,10 @@ public class EdFluidFunnel
// check for same fluid above (only source blocks) // check for same fluid above (only source blocks)
final int max_surface_search = (MAX_TRACKING_STEPS_PER_CYCLE_INTENSIVE/2)-steps; final int max_surface_search = (MAX_TRACKING_STEPS_PER_CYCLE_INTENSIVE/2)-steps;
for(int k=0; k<max_surface_search; ++k) { for(int k=0; k<max_surface_search; ++k) {
FluidState fs = get_fluidstate(pos.up()); FluidState fs = get_fluidstate(pos.above());
if(!can_pick(pos.up(), fs)) break; if(!can_pick(pos.above(), fs)) break;
fluidstate = fs; fluidstate = fs;
pos = pos.up(); pos = pos.above();
trail.push(pos); trail.push(pos);
} }
} }
@ -346,7 +346,7 @@ public class EdFluidFunnel
no_fluid_found_counter_ = 0; no_fluid_found_counter_ = 0;
search_offsets_ = null; search_offsets_ = null;
// probability reset, so it's not turteling too far away, mainly for large nether lava seas, not desert lakes. // probability reset, so it's not turteling too far away, mainly for large nether lava seas, not desert lakes.
if((++total_pick_counter_ > 50) && world.rand.nextInt(10)==0) last_pick_pos_ = collection_pos; if((++total_pick_counter_ > 50) && level.random.nextInt(10)==0) last_pick_pos_ = collection_pos;
//println("PASS " + steps + " - " + (pos.subtract(collection_pos))); //println("PASS " + steps + " - " + (pos.subtract(collection_pos)));
return true; return true;
} }
@ -357,7 +357,7 @@ public class EdFluidFunnel
} }
//println("FAIL=" + steps + " - " + (pos.subtract(collection_pos))); //println("FAIL=" + steps + " - " + (pos.subtract(collection_pos)));
//String s = new String(); for(BlockPos p:checked) s += "\n" + p; println(s); //String s = new String(); for(BlockPos p:checked) s += "\n" + p; println(s);
if(intensive_search_counter_ > 2) world.removeBlock(pos, false); if(intensive_search_counter_ > 2) level.removeBlock(pos, false);
last_pick_pos_ = collection_pos; last_pick_pos_ = collection_pos;
search_offsets_ = null; // try other search order search_offsets_ = null; // try other search order
++no_fluid_found_counter_; ++no_fluid_found_counter_;
@ -366,18 +366,18 @@ public class EdFluidFunnel
public void tick() public void tick()
{ {
if((world.isRemote) || (--tick_timer_ > 0)) return; if((level.isClientSide) || (--tick_timer_ > 0)) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
collection_timer_ += TICK_INTERVAL; collection_timer_ += TICK_INTERVAL;
final BlockState funnel_state = world.getBlockState(pos); final BlockState funnel_state = level.getBlockState(worldPosition);
if(!(funnel_state.getBlock() instanceof FluidFunnelBlock)) return; if(!(funnel_state.getBlock() instanceof FluidFunnelBlock)) return;
boolean dirty = false; boolean dirty = false;
// Collection // Collection
if((collection_timer_ >= COLLECTION_INTERVAL) && ((tank_==null) || (tank_.getFluidAmount() <= (TANK_CAPACITY-1000)))) { if((collection_timer_ >= COLLECTION_INTERVAL) && ((tank_==null) || (tank_.getFluidAmount() <= (TANK_CAPACITY-1000)))) {
collection_timer_ = 0; collection_timer_ = 0;
if(!world.isBlockPowered(pos)) { // redstone disable feature if(!level.hasNeighborSignal(worldPosition)) { // redstone disable feature
if(last_pick_pos_==null) last_pick_pos_ = pos.up(); if(last_pick_pos_==null) last_pick_pos_ = worldPosition.above();
TileEntity te = with_device_fluid_handler_collection ? (world.getTileEntity(pos.up())) : (null); TileEntity te = with_device_fluid_handler_collection ? (level.getBlockEntity(worldPosition.above())) : (null);
if(te != null) { if(te != null) {
IFluidHandler fh = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, Direction.DOWN).orElse(null); IFluidHandler fh = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, Direction.DOWN).orElse(null);
if(fh == null) { if(fh == null) {
@ -393,13 +393,13 @@ public class EdFluidFunnel
} }
} }
if(te==null) { if(te==null) {
if(try_collect(pos.up())) dirty = true; if(try_collect(worldPosition.above())) dirty = true;
} }
} }
} }
// Gravity fluid transfer // Gravity fluid transfer
if((tank_.getFluidAmount() >= 1000)) { if((tank_.getFluidAmount() >= 1000)) {
IFluidHandler fh = FluidUtil.getFluidHandler(world, pos.down(), Direction.UP).orElse(null); IFluidHandler fh = FluidUtil.getFluidHandler(level, worldPosition.below(), Direction.UP).orElse(null);
if(fh != null) { if(fh != null) {
FluidStack fs = new FluidStack(tank_.getFluid().getFluid(), 1000); FluidStack fs = new FluidStack(tank_.getFluid().getFluid(), 1000);
int nfilled = MathHelper.clamp(fh.fill(fs, FluidAction.EXECUTE), 0, 1000); int nfilled = MathHelper.clamp(fh.fill(fs, FluidAction.EXECUTE), 0, 1000);
@ -409,8 +409,8 @@ public class EdFluidFunnel
} }
// Block state // Block state
int fill_level = (tank_==null) ? 0 : (MathHelper.clamp(tank_.getFluidAmount()/1000,0, FluidFunnelBlock.FILL_LEVEL_MAX)); int fill_level = (tank_==null) ? 0 : (MathHelper.clamp(tank_.getFluidAmount()/1000,0, FluidFunnelBlock.FILL_LEVEL_MAX));
if(funnel_state.get(FluidFunnelBlock.FILL_LEVEL) != fill_level) world.setBlockState(pos, funnel_state.with(FluidFunnelBlock.FILL_LEVEL, fill_level), 2|16); if(funnel_state.getValue(FluidFunnelBlock.FILL_LEVEL) != fill_level) level.setBlock(worldPosition, funnel_state.setValue(FluidFunnelBlock.FILL_LEVEL, fill_level), 2|16);
if(dirty) markDirty(); if(dirty) setChanged();
} }
} }
} }

View file

@ -40,7 +40,6 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import wile.engineersdecor.ModConfig; import wile.engineersdecor.ModConfig;
import wile.engineersdecor.libmc.detail.Fluidics; import wile.engineersdecor.libmc.detail.Fluidics;
import wile.engineersdecor.ModContent; import wile.engineersdecor.ModContent;
import wile.engineersdecor.ModEngineersDecor;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -60,27 +59,27 @@ public class EdFreezer
public static final int PHASE_MAX = 4; public static final int PHASE_MAX = 4;
public static final IntegerProperty PHASE = IntegerProperty.create("phase", 0, PHASE_MAX); public static final IntegerProperty PHASE = IntegerProperty.create("phase", 0, PHASE_MAX);
public FreezerBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB) public FreezerBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(PHASE); } { super.createBlockStateDefinition(builder); builder.add(PHASE); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(PHASE, 0); } { return super.getStateForPlacement(context).setValue(PHASE, 0); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState state, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState state, World world, BlockPos pos)
{ return MathHelper.clamp((state.get(PHASE)*4), 0, 15); } { return MathHelper.clamp((state.getValue(PHASE)*4), 0, 15); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -92,7 +91,7 @@ public class EdFreezer
{ return new EdFreezer.FreezerTileEntity(); } { return new EdFreezer.FreezerTileEntity(); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{} {}
@Override @Override
@ -103,7 +102,7 @@ public class EdFreezer
public List<ItemStack> dropList(BlockState state, World world, TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof FreezerTileEntity)) return stacks; if(!(te instanceof FreezerTileEntity)) return stacks;
((FreezerTileEntity)te).reset_process(); ((FreezerTileEntity)te).reset_process();
stacks.add(new ItemStack(this, 1)); stacks.add(new ItemStack(this, 1));
@ -112,16 +111,16 @@ public class EdFreezer
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(player.isSneaking()) return ActionResultType.PASS; if(player.isShiftKeyDown()) return ActionResultType.PASS;
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
FreezerTileEntity te = getTe(world, pos); FreezerTileEntity te = getTe(world, pos);
if(te==null) return ActionResultType.FAIL; if(te==null) return ActionResultType.FAIL;
final ItemStack stack = player.getHeldItem(hand); final ItemStack stack = player.getItemInHand(hand);
boolean dirty = false; boolean dirty = false;
if(Fluidics.manualFluidHandlerInteraction(world, pos, null, player, hand)) { if(Fluidics.manualFluidHandlerInteraction(world, pos, null, player, hand)) {
world.playSound(null, pos, SoundEvents.ITEM_BUCKET_EMPTY, SoundCategory.BLOCKS, 0.5f, 1.4f); world.playSound(null, pos, SoundEvents.BUCKET_EMPTY, SoundCategory.BLOCKS, 0.5f, 1.4f);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
if(stack.getItem()==Items.WATER_BUCKET) { if(stack.getItem()==Items.WATER_BUCKET) {
@ -129,10 +128,10 @@ public class EdFreezer
} else if(stack.isEmpty()) { } else if(stack.isEmpty()) {
ItemStack ice = te.getIceItem(true); ItemStack ice = te.getIceItem(true);
if(!ice.isEmpty()) { if(!ice.isEmpty()) {
player.addItemStackToInventory(ice); player.addItem(ice);
world.playSound(null, pos, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.BLOCKS, 0.3f, 1.1f); world.playSound(null, pos, SoundEvents.ITEM_PICKUP, SoundCategory.BLOCKS, 0.3f, 1.1f);
} else { } else {
world.playSound(null, pos, SoundEvents.BLOCK_IRON_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 0.2f, 0.02f); world.playSound(null, pos, SoundEvents.IRON_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 0.2f, 0.02f);
} }
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} else { } else {
@ -151,7 +150,7 @@ public class EdFreezer
@Nullable @Nullable
private FreezerTileEntity getTe(World world, BlockPos pos) private FreezerTileEntity getTe(World world, BlockPos pos)
{ final TileEntity te=world.getTileEntity(pos); return (!(te instanceof FreezerTileEntity)) ? (null) : ((FreezerTileEntity)te); } { final TileEntity te=world.getBlockEntity(pos); return (!(te instanceof FreezerTileEntity)) ? (null) : ((FreezerTileEntity)te); }
} }
//-------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------
@ -249,17 +248,17 @@ public class EdFreezer
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt); return nbt; } { super.save(nbt); writenbt(nbt); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
energy_handler_.invalidate(); energy_handler_.invalidate();
fluid_handler_.invalidate(); fluid_handler_.invalidate();
item_handler_.invalidate(); item_handler_.invalidate();
@ -267,11 +266,11 @@ public class EdFreezer
// IItemHandler -------------------------------------------------------------------------------- // IItemHandler --------------------------------------------------------------------------------
private LazyOptional<IItemHandler> item_handler_ = LazyOptional.of(() -> (IItemHandler)new FreezerItemHandler(this)); private final LazyOptional<IItemHandler> item_handler_ = LazyOptional.of(() -> (IItemHandler)new FreezerItemHandler(this));
protected static class FreezerItemHandler implements IItemHandler protected static class FreezerItemHandler implements IItemHandler
{ {
private FreezerTileEntity te; private final FreezerTileEntity te;
FreezerItemHandler(FreezerTileEntity te) FreezerItemHandler(FreezerTileEntity te)
{ this.te = te; } { this.te = te; }
@ -338,7 +337,7 @@ public class EdFreezer
if(energy_stored_ >= MAX_ENERGY_BUFFER) return 0; if(energy_stored_ >= MAX_ENERGY_BUFFER) return 0;
int n = Math.min(maxReceive, (MAX_ENERGY_BUFFER - energy_stored_)); int n = Math.min(maxReceive, (MAX_ENERGY_BUFFER - energy_stored_));
if(n > MAX_ENERGY_TRANSFER) n = MAX_ENERGY_TRANSFER; if(n > MAX_ENERGY_TRANSFER) n = MAX_ENERGY_TRANSFER;
if(!simulate) {energy_stored_ += n; markDirty(); } if(!simulate) {energy_stored_ += n; setChanged(); }
return n; return n;
} }
@ -358,16 +357,16 @@ public class EdFreezer
@Override @Override
public void tick() public void tick()
{ {
if(world.isRemote) return; if(level.isClientSide) return;
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
BlockState state = world.getBlockState(pos); BlockState state = level.getBlockState(worldPosition);
if(!(state.getBlock() instanceof FreezerBlock)) return; if(!(state.getBlock() instanceof FreezerBlock)) return;
boolean dirty = false; boolean dirty = false;
final int last_phase = phase(); final int last_phase = phase();
if(tank_.getFluidAmount() < 1000) { if(tank_.getFluidAmount() < 1000) {
progress_ = 0; progress_ = 0;
} else if((energy_stored_ <= 0) || (world.isBlockPowered(pos))) { } else if((energy_stored_ <= 0) || (level.hasNeighborSignal(worldPosition))) {
progress_ = MathHelper.clamp(progress_-reheat_rate, 0,100); progress_ = MathHelper.clamp(progress_-reheat_rate, 0,100);
} else if(progress_ >= 100) { } else if(progress_ >= 100) {
progress_ = 100; progress_ = 100;
@ -378,18 +377,18 @@ public class EdFreezer
} }
int new_phase = phase(); int new_phase = phase();
if(new_phase > last_phase) { if(new_phase > last_phase) {
world.playSound(null, pos, SoundEvents.BLOCK_SAND_FALL, SoundCategory.BLOCKS, 0.2f, 0.7f); level.playSound(null, worldPosition, SoundEvents.SAND_FALL, SoundCategory.BLOCKS, 0.2f, 0.7f);
} else if(new_phase < last_phase) { } else if(new_phase < last_phase) {
world.playSound(null, pos, SoundEvents.BLOCK_SAND_FALL, SoundCategory.BLOCKS, 0.2f, 0.7f); level.playSound(null, worldPosition, SoundEvents.SAND_FALL, SoundCategory.BLOCKS, 0.2f, 0.7f);
} }
// Block state // Block state
if((force_block_update_ || (state.get(FreezerBlock.PHASE) != new_phase))) { if((force_block_update_ || (state.getValue(FreezerBlock.PHASE) != new_phase))) {
state = state.with(FreezerBlock.PHASE, new_phase); state = state.setValue(FreezerBlock.PHASE, new_phase);
world.setBlockState(pos, state,3|16); level.setBlock(worldPosition, state,3|16);
world.notifyNeighborsOfStateChange(getPos(), state.getBlock()); level.updateNeighborsAt(getBlockPos(), state.getBlock());
force_block_update_ = false; force_block_update_ = false;
} }
if(dirty) markDirty(); if(dirty) setChanged();
} }
} }
} }

View file

@ -27,6 +27,7 @@ import net.minecraft.util.SoundEvents;
import net.minecraft.state.BooleanProperty; import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer; import net.minecraft.state.StateContainer;
import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.world.IWorldReader; import net.minecraft.world.IWorldReader;
@ -71,6 +72,7 @@ import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class EdFurnace public class EdFurnace
{ {
public static void on_config(int speed_percent, int fuel_efficiency_percent, int boost_energy_per_tick, String accepted_heaters_csv) public static void on_config(int speed_percent, int fuel_efficiency_percent, int boost_energy_per_tick, String accepted_heaters_csv)
@ -84,33 +86,33 @@ public class EdFurnace
{ {
public static final BooleanProperty LIT = RedstoneTorchBlock.LIT; public static final BooleanProperty LIT = RedstoneTorchBlock.LIT;
public FurnaceBlock(long config, Block.Properties properties, final AxisAlignedBB[] unrotatedAABB) public FurnaceBlock(long config, AbstractBlock.Properties properties, final AxisAlignedBB[] unrotatedAABB)
{ super(config, properties, unrotatedAABB); setDefaultState(super.getDefaultState().with(LIT, false)); } { super(config, properties, unrotatedAABB); registerDefaultState(super.defaultBlockState().setValue(LIT, false)); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(LIT); } { super.createBlockStateDefinition(builder); builder.add(LIT); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getLightValue(BlockState state, IBlockReader world, BlockPos pos) public int getLightValue(BlockState state, IBlockReader world, BlockPos pos)
{ return state.get(LIT) ? super.getLightValue(state, world, pos) : 0; } { return state.getValue(LIT) ? super.getLightValue(state, world, pos) : 0; }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(LIT, false); } { return super.getStateForPlacement(context).setValue(LIT, false); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState blockState, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState blockState, World world, BlockPos pos)
{ {
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
return (te instanceof FurnaceTileEntity) ? ((FurnaceTileEntity)te).getComparatorOutput() : 0; return (te instanceof FurnaceTileEntity) ? ((FurnaceTileEntity)te).getComparatorOutput() : 0;
} }
@ -128,19 +130,19 @@ public class EdFurnace
{ return new FurnaceTileEntity(); } { return new FurnaceTileEntity(); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
world.setBlockState(pos, state.with(LIT, false)); world.setBlockAndUpdate(pos, state.setValue(LIT, false));
if(world.isRemote) return; if(world.isClientSide) return;
if((!stack.hasTag()) || (!stack.getTag().contains("inventory"))) return; if((!stack.hasTag()) || (!stack.getTag().contains("inventory"))) return;
CompoundNBT inventory_nbt = stack.getTag().getCompound("inventory"); CompoundNBT inventory_nbt = stack.getTag().getCompound("inventory");
if(inventory_nbt.isEmpty()) return; if(inventory_nbt.isEmpty()) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof FurnaceTileEntity)) return; if(!(te instanceof FurnaceTileEntity)) return;
final FurnaceTileEntity bte = ((FurnaceTileEntity)te); final FurnaceTileEntity bte = ((FurnaceTileEntity)te);
bte.readnbt(inventory_nbt); bte.readnbt(inventory_nbt);
bte.markDirty(); bte.setChanged();
world.setBlockState(pos, state.with(LIT, bte.burning())); world.setBlockAndUpdate(pos, state.setValue(LIT, bte.burning()));
} }
@Override @Override
@ -150,7 +152,7 @@ public class EdFurnace
@Override @Override
public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) { public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof FurnaceTileEntity)) return stacks; if(!(te instanceof FurnaceTileEntity)) return stacks;
if(!explosion) { if(!explosion) {
ItemStack stack = new ItemStack(this, 1); ItemStack stack = new ItemStack(this, 1);
@ -170,14 +172,14 @@ public class EdFurnace
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof FurnaceTileEntity)) return ActionResultType.FAIL; if(!(te instanceof FurnaceTileEntity)) return ActionResultType.FAIL;
if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL; if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL;
NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te); NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te);
player.addStat(Stats.INTERACT_WITH_FURNACE); player.awardStat(Stats.INTERACT_WITH_FURNACE);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@ -185,13 +187,13 @@ public class EdFurnace
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void animateTick(BlockState state, World world, BlockPos pos, Random rnd) public void animateTick(BlockState state, World world, BlockPos pos, Random rnd)
{ {
if((state.getBlock()!=this) || (!state.get(LIT))) return; if((state.getBlock()!=this) || (!state.getValue(LIT))) return;
final double rv = rnd.nextDouble(); final double rv = rnd.nextDouble();
if(rv > 0.5) return; if(rv > 0.5) return;
final double x=0.5+pos.getX(), y=0.5+pos.getY(), z=0.5+pos.getZ(); final double x=0.5+pos.getX(), y=0.5+pos.getY(), z=0.5+pos.getZ();
final double xc=0.52, xr=rnd.nextDouble()*0.4-0.2, yr=(y-0.3+rnd.nextDouble()*0.2); final double xc=0.52, xr=rnd.nextDouble()*0.4-0.2, yr=(y-0.3+rnd.nextDouble()*0.2);
if(rv < 0.1d) world.playSound(x, y, z, SoundEvents.BLOCK_FURNACE_FIRE_CRACKLE, SoundCategory.BLOCKS, 0.4f, 0.5f, false); if(rv < 0.1d) world.playLocalSound(x, y, z, SoundEvents.FURNACE_FIRE_CRACKLE, SoundCategory.BLOCKS, 0.4f, 0.5f, false);
switch(state.get(HORIZONTAL_FACING)) { switch(state.getValue(HORIZONTAL_FACING)) {
case WEST: world.addParticle(ParticleTypes.SMOKE, x-xc, yr, z+xr, 0.0, 0.0, 0.0); break; case WEST: world.addParticle(ParticleTypes.SMOKE, x-xc, yr, z+xr, 0.0, 0.0, 0.0); break;
case EAST: world.addParticle(ParticleTypes.SMOKE, x+xc, yr, z+xr, 0.0, 0.0, 0.0); break; case EAST: world.addParticle(ParticleTypes.SMOKE, x+xc, yr, z+xr, 0.0, 0.0, 0.0); break;
case NORTH: world.addParticle(ParticleTypes.SMOKE, x+xr, yr, z-xc, 0.0, 0.0, 0.0); break; case NORTH: world.addParticle(ParticleTypes.SMOKE, x+xr, yr, z-xc, 0.0, 0.0, 0.0); break;
@ -233,7 +235,7 @@ public class EdFurnace
private static double proc_fuel_efficiency_ = 1.0; private static double proc_fuel_efficiency_ = 1.0;
private static double proc_speed_ = 1.2; private static double proc_speed_ = 1.2;
private static int boost_energy_consumption = DEFAULT_BOOST_ENERGY * TICK_INTERVAL; private static int boost_energy_consumption = DEFAULT_BOOST_ENERGY * TICK_INTERVAL;
private static Set<Item> accepted_heaters_ = new HashSet<>(); private static final Set<Item> accepted_heaters_ = new HashSet<>();
public static void on_config(int speed_percent, int fuel_efficiency_percent, int boost_energy_per_tick, String accepted_heaters_csv) public static void on_config(int speed_percent, int fuel_efficiency_percent, int boost_energy_per_tick, String accepted_heaters_csv)
{ {
@ -250,7 +252,7 @@ public class EdFurnace
ResourceLocation rl = new ResourceLocation(rlstr); ResourceLocation rl = new ResourceLocation(rlstr);
Item heater = ForgeRegistries.ITEMS.getValue(rl); Item heater = ForgeRegistries.ITEMS.getValue(rl);
if((heater==null) || (heater==Items.AIR)) { if((heater==null) || (heater==Items.AIR)) {
ModConfig.log("Furnace accepted heater config: Skipped '" + rl.toString() + "', item not found/mod not installed."); ModConfig.log("Furnace accepted heater config: Skipped '" + rl + "', item not found/mod not installed.");
} else { } else {
accepted_heaters_.add(heater); accepted_heaters_.add(heater);
} }
@ -272,7 +274,7 @@ public class EdFurnace
protected int burntime_left_; protected int burntime_left_;
protected int field_is_burning_; protected int field_is_burning_;
protected float xp_stored_; protected float xp_stored_;
protected @Nullable IRecipe current_recipe_ = null; protected @Nullable IRecipe<?> current_recipe_ = null;
private int fuel_burntime_; private int fuel_burntime_;
private int field_proc_time_elapsed_; private int field_proc_time_elapsed_;
private boolean heater_inserted_ = false; private boolean heater_inserted_ = false;
@ -294,16 +296,16 @@ public class EdFurnace
super(te_type); super(te_type);
inventory_ = new StorageInventory(this, num_slots) { inventory_ = new StorageInventory(this, num_slots) {
@Override @Override
public void setInventorySlotContents(int index, ItemStack stack) public void setItem(int index, ItemStack stack)
{ {
ItemStack slot_stack = stacks_.get(index); ItemStack slot_stack = stacks_.get(index);
boolean already_in_slot = (!stack.isEmpty()) && (Inventories.areItemStacksIdentical(stack, slot_stack)); boolean already_in_slot = (!stack.isEmpty()) && (Inventories.areItemStacksIdentical(stack, slot_stack));
stacks_.set(index, stack); stacks_.set(index, stack);
if(stack.getCount() > getInventoryStackLimit()) stack.setCount(getInventoryStackLimit()); if(stack.getCount() > getMaxStackSize()) stack.setCount(getMaxStackSize());
if((index == SMELTING_INPUT_SLOT_NO) && (!already_in_slot)) { if((index == SMELTING_INPUT_SLOT_NO) && (!already_in_slot)) {
proc_time_needed_ = getSmeltingTimeNeeded(world, stack); proc_time_needed_ = getSmeltingTimeNeeded(level, stack);
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
markDirty(); setChanged();
} }
} }
}; };
@ -322,13 +324,13 @@ public class EdFurnace
case AUX_1_SLOT_NO: case AUX_1_SLOT_NO:
return true; return true;
default: { default: {
ItemStack slot_stack = inventory_.getStackInSlot(FIFO_FUEL_1_SLOT_NO); ItemStack slot_stack = inventory_.getItem(FIFO_FUEL_1_SLOT_NO);
return isFuel(world, stack) || FurnaceFuelSlot.isBucket(stack) && (slot_stack.getItem() != Items.BUCKET); return isFuel(level, stack) || FurnaceFuelSlot.isBucket(stack) && (slot_stack.getItem() != Items.BUCKET);
} }
} }
}); });
item_extraction_handler_ = MappedItemHandler.createExtractionHandler(inventory_, item_extraction_handler_ = MappedItemHandler.createExtractionHandler(inventory_,
(slot,stack)->(slot!=SMELTING_FUEL_SLOT_NO) || (stack.getItem()==Items.BUCKET) || (!isFuel(getWorld(), stack)), (slot,stack)->(slot!=SMELTING_FUEL_SLOT_NO) || (stack.getItem()==Items.BUCKET) || (!isFuel(getLevel(), stack)),
Arrays.asList(FIFO_OUTPUT_0_SLOT_NO, FIFO_OUTPUT_1_SLOT_NO, SMELTING_FUEL_SLOT_NO) Arrays.asList(FIFO_OUTPUT_0_SLOT_NO, FIFO_OUTPUT_1_SLOT_NO, SMELTING_FUEL_SLOT_NO)
); );
item_insertion_handler_ = MappedItemHandler.createInsertionHandler(inventory_, item_insertion_handler_ = MappedItemHandler.createInsertionHandler(inventory_,
@ -351,7 +353,7 @@ public class EdFurnace
public void reset() public void reset()
{ {
inventory_.clear(); inventory_.clearContent();
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
proc_time_needed_ = 0; proc_time_needed_ = 0;
burntime_left_ = 0; burntime_left_ = 0;
@ -386,13 +388,13 @@ public class EdFurnace
public int getComparatorOutput() public int getComparatorOutput()
{ {
if(inventory_.getStackInSlot(FIFO_FUEL_0_SLOT_NO).isEmpty() && inventory_.getStackInSlot(FIFO_FUEL_1_SLOT_NO).isEmpty() && inventory_.getStackInSlot(SMELTING_FUEL_SLOT_NO).isEmpty()) { if(inventory_.getItem(FIFO_FUEL_0_SLOT_NO).isEmpty() && inventory_.getItem(FIFO_FUEL_1_SLOT_NO).isEmpty() && inventory_.getItem(SMELTING_FUEL_SLOT_NO).isEmpty()) {
return 0; // fuel completely empty return 0; // fuel completely empty
} else { } else {
return ( return (
(inventory_.getStackInSlot(FIFO_INPUT_1_SLOT_NO).isEmpty() ? 0 : 5) + (inventory_.getItem(FIFO_INPUT_1_SLOT_NO).isEmpty() ? 0 : 5) +
(inventory_.getStackInSlot(FIFO_INPUT_0_SLOT_NO).isEmpty() ? 0 : 5) + (inventory_.getItem(FIFO_INPUT_0_SLOT_NO).isEmpty() ? 0 : 5) +
(inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO).isEmpty() ? 0 : 5) (inventory_.getItem(SMELTING_INPUT_SLOT_NO).isEmpty() ? 0 : 5)
); );
} }
} }
@ -400,17 +402,17 @@ public class EdFurnace
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt); return nbt; } { super.save(nbt); writenbt(nbt); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
item_extraction_handler_.invalidate(); item_extraction_handler_.invalidate();
item_insertion_handler_.invalidate(); item_insertion_handler_.invalidate();
item_fuel_insertion_handler_.invalidate(); item_fuel_insertion_handler_.invalidate();
@ -421,7 +423,7 @@ public class EdFurnace
@Override @Override
public ITextComponent getName() public ITextComponent getName()
{ final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getTranslationKey() : "Lab furnace"); } { final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getDescriptionId() : "Lab furnace"); }
@Override @Override
public boolean hasCustomName() public boolean hasCustomName()
@ -439,7 +441,7 @@ public class EdFurnace
@Override @Override
public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player ) public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player )
{ return new FurnaceContainer(id, inventory, inventory_, IWorldPosCallable.of(world, pos), fields); } { return new FurnaceContainer(id, inventory, inventory_, IWorldPosCallable.create(level, worldPosition), fields); }
// Fields ----------------------------------------------------------------------------------------------- // Fields -----------------------------------------------------------------------------------------------
@ -492,12 +494,12 @@ public class EdFurnace
{ {
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
final BlockState state = world.getBlockState(pos); final BlockState state = level.getBlockState(worldPosition);
if(!(state.getBlock() instanceof FurnaceBlock)) return; if(!(state.getBlock() instanceof FurnaceBlock)) return;
final boolean was_burning = burning(); final boolean was_burning = burning();
if(was_burning) burntime_left_ -= TICK_INTERVAL; if(was_burning) burntime_left_ -= TICK_INTERVAL;
if(burntime_left_ < 0) burntime_left_ = 0; if(burntime_left_ < 0) burntime_left_ = 0;
if(world.isRemote) return; if(level.isClientSide) return;
boolean dirty = false; boolean dirty = false;
if(--fifo_timer_ <= 0) { if(--fifo_timer_ <= 0) {
fifo_timer_ = FIFO_INTERVAL/TICK_INTERVAL; fifo_timer_ = FIFO_INTERVAL/TICK_INTERVAL;
@ -509,26 +511,26 @@ public class EdFurnace
if(transferItems(FIFO_INPUT_0_SLOT_NO, SMELTING_INPUT_SLOT_NO, 1)) dirty = true; if(transferItems(FIFO_INPUT_0_SLOT_NO, SMELTING_INPUT_SLOT_NO, 1)) dirty = true;
if(transferItems(FIFO_INPUT_1_SLOT_NO, FIFO_INPUT_0_SLOT_NO, 1)) dirty = true; if(transferItems(FIFO_INPUT_1_SLOT_NO, FIFO_INPUT_0_SLOT_NO, 1)) dirty = true;
heater_inserted_ = accepted_heaters_.isEmpty() // without IE always allow electrical boost heater_inserted_ = accepted_heaters_.isEmpty() // without IE always allow electrical boost
|| accepted_heaters_.contains(inventory_.getStackInSlot(AUX_0_SLOT_NO).getItem()) || accepted_heaters_.contains(inventory_.getItem(AUX_0_SLOT_NO).getItem())
|| accepted_heaters_.contains(inventory_.getStackInSlot(AUX_1_SLOT_NO).getItem()); || accepted_heaters_.contains(inventory_.getItem(AUX_1_SLOT_NO).getItem());
} }
ItemStack fuel = inventory_.getStackInSlot(SMELTING_FUEL_SLOT_NO); ItemStack fuel = inventory_.getItem(SMELTING_FUEL_SLOT_NO);
if(burning() || (!fuel.isEmpty()) && (!(inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)).isEmpty())) { if(burning() || (!fuel.isEmpty()) && (!(inventory_.getItem(SMELTING_INPUT_SLOT_NO)).isEmpty())) {
IRecipe last_recipe = currentRecipe(); IRecipe<?> last_recipe = currentRecipe();
updateCurrentRecipe(); updateCurrentRecipe();
if(currentRecipe() != last_recipe) { if(currentRecipe() != last_recipe) {
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
proc_time_needed_ = getSmeltingTimeNeeded(world, inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)); proc_time_needed_ = getSmeltingTimeNeeded(level, inventory_.getItem(SMELTING_INPUT_SLOT_NO));
} }
if(!burning() && canSmeltCurrentItem()) { if(!burning() && canSmeltCurrentItem()) {
burntime_left_ = (int)MathHelper.clamp((proc_fuel_efficiency_ * getFuelBurntime(world, fuel)), 0, MAX_BURNTIME); burntime_left_ = (int)MathHelper.clamp((proc_fuel_efficiency_ * getFuelBurntime(level, fuel)), 0, MAX_BURNTIME);
fuel_burntime_ = (int)MathHelper.clamp(((double)burntime_left_)/((proc_speed_ > 0) ? proc_speed_ : 1), 1, MAX_BURNTIME); fuel_burntime_ = (int)MathHelper.clamp(((double)burntime_left_)/((proc_speed_ > 0) ? proc_speed_ : 1), 1, MAX_BURNTIME);
if(burning()) { if(burning()) {
dirty = true; dirty = true;
if(!fuel.isEmpty()) { if(!fuel.isEmpty()) {
Item fuel_item = fuel.getItem(); Item fuel_item = fuel.getItem();
fuel.shrink(1); fuel.shrink(1);
if(fuel.isEmpty()) inventory_.setInventorySlotContents(SMELTING_FUEL_SLOT_NO, fuel_item.getContainerItem(fuel)); if(fuel.isEmpty()) inventory_.setItem(SMELTING_FUEL_SLOT_NO, fuel_item.getContainerItem(fuel));
} }
} }
} }
@ -539,7 +541,7 @@ public class EdFurnace
} }
if(proc_time_elapsed_ >= proc_time_needed_) { if(proc_time_elapsed_ >= proc_time_needed_) {
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
proc_time_needed_ = getSmeltingTimeNeeded(world, inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)); proc_time_needed_ = getSmeltingTimeNeeded(level, inventory_.getItem(SMELTING_INPUT_SLOT_NO));
smeltCurrentItem(); smeltCurrentItem();
dirty = true; dirty = true;
} }
@ -551,10 +553,10 @@ public class EdFurnace
} }
if(was_burning != burning()) { if(was_burning != burning()) {
dirty = true; dirty = true;
world.setBlockState(pos, state.with(FurnaceBlock.LIT, burning())); level.setBlockAndUpdate(worldPosition, state.setValue(FurnaceBlock.LIT, burning()));
} }
if(dirty) { if(dirty) {
markDirty(); setChanged();
} }
field_is_burning_ = this.burning() ? 1 : 0; field_is_burning_ = this.burning() ? 1 : 0;
field_proc_time_elapsed_ = (int)proc_time_elapsed_; field_proc_time_elapsed_ = (int)proc_time_elapsed_;
@ -567,8 +569,8 @@ public class EdFurnace
{ {
if(stack.isEmpty()) return null; if(stack.isEmpty()) return null;
Inventory inventory = new Inventory(3); Inventory inventory = new Inventory(3);
inventory.setInventorySlotContents(0, stack); inventory.setItem(0, stack);
return world.getRecipeManager().getRecipe(recipe_type, inventory, world).orElse(null); return world.getRecipeManager().getRecipeFor(recipe_type, inventory, world).orElse(null);
} }
public boolean burning() public boolean burning()
@ -579,20 +581,20 @@ public class EdFurnace
if(stack.isEmpty()) return 0; if(stack.isEmpty()) return 0;
AbstractCookingRecipe recipe = getSmeltingResult(RECIPE_TYPE, world, stack); AbstractCookingRecipe recipe = getSmeltingResult(RECIPE_TYPE, world, stack);
if(recipe == null) return 0; if(recipe == null) return 0;
int t = recipe.getCookTime(); int t = recipe.getCookingTime();
return (t<=0) ? DEFAULT_SMELTING_TIME : t; return (t<=0) ? DEFAULT_SMELTING_TIME : t;
} }
private boolean transferItems(final int index_from, final int index_to, int count) private boolean transferItems(final int index_from, final int index_to, int count)
{ {
ItemStack from = inventory_.getStackInSlot(index_from); ItemStack from = inventory_.getItem(index_from);
if(from.isEmpty()) return false; if(from.isEmpty()) return false;
ItemStack to = inventory_.getStackInSlot(index_to); ItemStack to = inventory_.getItem(index_to);
if(from.getCount() < count) count = from.getCount(); if(from.getCount() < count) count = from.getCount();
if(count <= 0) return false; if(count <= 0) return false;
boolean changed = true; boolean changed = true;
if(to.isEmpty()) { if(to.isEmpty()) {
inventory_.setInventorySlotContents(index_to, from.split(count)); inventory_.setItem(index_to, from.split(count));
} else if(to.getCount() >= to.getMaxStackSize()) { } else if(to.getCount() >= to.getMaxStackSize()) {
changed = false; changed = false;
} else if(Inventories.areItemStacksDifferent(from, to)) { } else if(Inventories.areItemStacksDifferent(from, to)) {
@ -607,7 +609,7 @@ public class EdFurnace
} }
} }
if(from.isEmpty() && from!=ItemStack.EMPTY) { if(from.isEmpty() && from!=ItemStack.EMPTY) {
inventory_.setInventorySlotContents(index_from, ItemStack.EMPTY); inventory_.setItem(index_from, ItemStack.EMPTY);
changed = true; changed = true;
} }
return changed; return changed;
@ -615,25 +617,25 @@ public class EdFurnace
protected boolean canSmeltCurrentItem() protected boolean canSmeltCurrentItem()
{ {
if((currentRecipe()==null) || (inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO).isEmpty())) return false; if((currentRecipe()==null) || (inventory_.getItem(SMELTING_INPUT_SLOT_NO).isEmpty())) return false;
final ItemStack recipe_result_items = getSmeltingResult(inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO)); final ItemStack recipe_result_items = getSmeltingResult(inventory_.getItem(SMELTING_INPUT_SLOT_NO));
if(recipe_result_items.isEmpty()) return false; if(recipe_result_items.isEmpty()) return false;
final ItemStack result_stack = inventory_.getStackInSlot(SMELTING_OUTPUT_SLOT_NO); final ItemStack result_stack = inventory_.getItem(SMELTING_OUTPUT_SLOT_NO);
if(result_stack.isEmpty()) return true; if(result_stack.isEmpty()) return true;
if(!result_stack.isItemEqual(recipe_result_items)) return false; if(!result_stack.sameItem(recipe_result_items)) return false;
if(result_stack.getCount() + recipe_result_items.getCount() <= inventory_.getInventoryStackLimit() && result_stack.getCount() + recipe_result_items.getCount() <= result_stack.getMaxStackSize()) return true; if(result_stack.getCount() + recipe_result_items.getCount() <= inventory_.getMaxStackSize() && result_stack.getCount() + recipe_result_items.getCount() <= result_stack.getMaxStackSize()) return true;
return result_stack.getCount() + recipe_result_items.getCount() <= recipe_result_items.getMaxStackSize(); return result_stack.getCount() + recipe_result_items.getCount() <= recipe_result_items.getMaxStackSize();
} }
protected void smeltCurrentItem() protected void smeltCurrentItem()
{ {
if(!canSmeltCurrentItem()) return; if(!canSmeltCurrentItem()) return;
final ItemStack smelting_input_stack = inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO); final ItemStack smelting_input_stack = inventory_.getItem(SMELTING_INPUT_SLOT_NO);
final ItemStack recipe_result_items = getSmeltingResult(smelting_input_stack); final ItemStack recipe_result_items = getSmeltingResult(smelting_input_stack);
final ItemStack smelting_output_stack = inventory_.getStackInSlot(SMELTING_OUTPUT_SLOT_NO); final ItemStack smelting_output_stack = inventory_.getItem(SMELTING_OUTPUT_SLOT_NO);
final float xp = getCurrentSmeltingXp(smelting_output_stack); final float xp = getCurrentSmeltingXp(smelting_output_stack);
if(smelting_output_stack.isEmpty()) { if(smelting_output_stack.isEmpty()) {
inventory_.setInventorySlotContents(SMELTING_OUTPUT_SLOT_NO, recipe_result_items.copy()); inventory_.setItem(SMELTING_OUTPUT_SLOT_NO, recipe_result_items.copy());
} else if(smelting_output_stack.getItem() == recipe_result_items.getItem()) { } else if(smelting_output_stack.getItem() == recipe_result_items.getItem()) {
smelting_output_stack.grow(recipe_result_items.getCount()); smelting_output_stack.grow(recipe_result_items.getCount());
} }
@ -645,7 +647,7 @@ public class EdFurnace
{ {
if(stack.isEmpty()) return 0; if(stack.isEmpty()) return 0;
int t = ForgeHooks.getBurnTime(stack); int t = ForgeHooks.getBurnTime(stack);
return (t<0) ? 0 : t; return Math.max(t, 0);
} }
public static boolean isFuel(World world, ItemStack stack) public static boolean isFuel(World world, ItemStack stack)
@ -662,7 +664,7 @@ public class EdFurnace
} }
public ItemStack getSmeltingResult(final ItemStack stack) public ItemStack getSmeltingResult(final ItemStack stack)
{ return (currentRecipe()==null) ? (ItemStack.EMPTY) : (currentRecipe().getRecipeOutput()); } { return (currentRecipe()==null) ? (ItemStack.EMPTY) : (currentRecipe().getResultItem()); }
public float getCurrentSmeltingXp(final ItemStack stack) public float getCurrentSmeltingXp(final ItemStack stack)
{ {
@ -674,11 +676,11 @@ public class EdFurnace
{ return getSmeltingResult(RECIPE_TYPE, world, stack) != null; } { return getSmeltingResult(RECIPE_TYPE, world, stack) != null; }
@Nullable @Nullable
protected IRecipe currentRecipe() protected IRecipe<?> currentRecipe()
{ return current_recipe_; } { return current_recipe_; }
protected void updateCurrentRecipe() protected void updateCurrentRecipe()
{ setCurrentRecipe(getSmeltingResult(RECIPE_TYPE, getWorld(), inventory_.getStackInSlot(SMELTING_INPUT_SLOT_NO))); } { setCurrentRecipe(getSmeltingResult(RECIPE_TYPE, getLevel(), inventory_.getItem(SMELTING_INPUT_SLOT_NO))); }
protected void setCurrentRecipe(IRecipe<?> recipe) protected void setCurrentRecipe(IRecipe<?> recipe)
{ current_recipe_ = recipe; } { current_recipe_ = recipe; }
@ -720,32 +722,32 @@ public class EdFurnace
{ super(inventory, index, xpos, ypos); inventory_ = inventory; player_ = player; } { super(inventory, index, xpos, ypos); inventory_ = inventory; player_ = player; }
@Override @Override
public boolean isItemValid(ItemStack stack) public boolean mayPlace(ItemStack stack)
{ return false; } { return false; }
@Override @Override
public ItemStack decrStackSize(int amount) public ItemStack remove(int amount)
{ removeCount += getHasStack() ? Math.min(amount, getStack().getCount()) : 0; return super.decrStackSize(amount); } { removeCount += hasItem() ? Math.min(amount, getItem().getCount()) : 0; return super.remove(amount); }
@Override @Override
public ItemStack onTake(PlayerEntity thePlayer, ItemStack stack) public ItemStack onTake(PlayerEntity thePlayer, ItemStack stack)
{ onCrafting(stack); super.onTake(thePlayer, stack); return stack; } { checkTakeAchievements(stack); super.onTake(thePlayer, stack); return stack; }
@Override @Override
protected void onCrafting(ItemStack stack, int amount) protected void onQuickCraft(ItemStack stack, int amount)
{ removeCount += amount; onCrafting(stack); } { removeCount += amount; checkTakeAchievements(stack); }
@Override @Override
protected void onCrafting(ItemStack stack) protected void checkTakeAchievements(ItemStack stack)
{ {
stack.onCrafting(player_.world, player_, removeCount); stack.onCraftedBy(player_.level, player_, removeCount);
if((!player_.world.isRemote()) && (inventory_ instanceof StorageInventory)) { if((!player_.level.isClientSide()) && (inventory_ instanceof StorageInventory)) {
FurnaceTileEntity te = (FurnaceTileEntity)(((StorageInventory)inventory_).getTileEntity()); FurnaceTileEntity te = (FurnaceTileEntity)(((StorageInventory)inventory_).getTileEntity());
int xp = te.consumeSmeltingExperience(stack); int xp = te.consumeSmeltingExperience(stack);
while(xp > 0) { while(xp > 0) {
int k = ExperienceOrbEntity.getXPSplit(xp); int k = ExperienceOrbEntity.getExperienceValue(xp);
xp -= k; xp -= k;
player_.world.addEntity((new ExperienceOrbEntity(player_.world, player_.getPosition().getX(), player_.getPosition().getY()+0.5, player_.getPosition().getZ()+0.5, k))); player_.level.addFreshEntity((new ExperienceOrbEntity(player_.level, player_.blockPosition().getX(), player_.blockPosition().getY()+0.5, player_.blockPosition().getZ()+0.5, k)));
} }
} }
removeCount = 0; removeCount = 0;
@ -761,12 +763,12 @@ public class EdFurnace
{ super(inventory, index, xpos, ypos); container_=container; } { super(inventory, index, xpos, ypos); container_=container; }
@Override @Override
public boolean isItemValid(ItemStack stack) public boolean mayPlace(ItemStack stack)
{ return isBucket(stack) || (FurnaceTileEntity.isFuel(container_.world(), stack)); } { return isBucket(stack) || (FurnaceTileEntity.isFuel(container_.world(), stack)); }
@Override @Override
public int getItemStackLimit(ItemStack stack) public int getMaxStackSize(ItemStack stack)
{ return isBucket(stack) ? 1 : super.getItemStackLimit(stack); } { return isBucket(stack) ? 1 : super.getMaxStackSize(stack); }
protected static boolean isBucket(ItemStack stack) protected static boolean isBucket(ItemStack stack)
{ return (stack.getItem()==Items.BUCKET); } { return (stack.getItem()==Items.BUCKET); }
@ -784,10 +786,10 @@ public class EdFurnace
public int field(int index) { return fields_.get(index); } public int field(int index) { return fields_.get(index); }
public PlayerEntity player() { return player_ ; } public PlayerEntity player() { return player_ ; }
public IInventory inventory() { return inventory_ ; } public IInventory inventory() { return inventory_ ; }
public World world() { return player_.world; } public World world() { return player_.level; }
public FurnaceContainer(int cid, PlayerInventory player_inventory) public FurnaceContainer(int cid, PlayerInventory player_inventory)
{ this(cid, player_inventory, new Inventory(FurnaceTileEntity.NUM_OF_SLOTS), IWorldPosCallable.DUMMY, new IntArray(FurnaceTileEntity.NUM_OF_FIELDS)); } { this(cid, player_inventory, new Inventory(FurnaceTileEntity.NUM_OF_SLOTS), IWorldPosCallable.NULL, new IntArray(FurnaceTileEntity.NUM_OF_FIELDS)); }
private FurnaceContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields) private FurnaceContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields)
{ {
@ -816,50 +818,50 @@ public class EdFurnace
addSlot(new Slot(player_inventory, x+y*9+9, 8+x*18, 86+y*18)); // player slots: 9..35 addSlot(new Slot(player_inventory, x+y*9+9, 8+x*18, 86+y*18)); // player slots: 9..35
} }
} }
this.trackIntArray(fields_); // === Add reference holders this.addDataSlots(fields_); // === Add reference holders
} }
@Override @Override
public boolean canInteractWith(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return inventory_.isUsableByPlayer(player); } { return inventory_.stillValid(player); }
@Override @Override
public ItemStack transferStackInSlot(PlayerEntity player, int index) public ItemStack quickMoveStack(PlayerEntity player, int index)
{ {
Slot slot = getSlot(index); Slot slot = getSlot(index);
if((slot==null) || (!slot.getHasStack())) return ItemStack.EMPTY; if((slot==null) || (!slot.hasItem())) return ItemStack.EMPTY;
ItemStack slot_stack = slot.getStack(); ItemStack slot_stack = slot.getItem();
ItemStack transferred = slot_stack.copy(); ItemStack transferred = slot_stack.copy();
if((index==2) || (index==7) || (index==8)) { if((index==2) || (index==7) || (index==8)) {
// Output slots // Output slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, true)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, true)) return ItemStack.EMPTY;
slot.onSlotChange(slot_stack, transferred); slot.onQuickCraft(slot_stack, transferred);
} else if((index==0) || (index==3) || (index==4)) { } else if((index==0) || (index==3) || (index==4)) {
// Input slots // Input slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index==1) || (index==5) || (index==6)) { } else if((index==1) || (index==5) || (index==6)) {
// Fuel slots // Fuel slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index==9) || (index==10)) { } else if((index==9) || (index==10)) {
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) {
// Player inventory // Player inventory
if(FurnaceTileEntity.canSmelt(world(), slot_stack)) { if(FurnaceTileEntity.canSmelt(world(), slot_stack)) {
if( if(
(!mergeItemStack(slot_stack, 0, 1, false)) && // smelting input (!moveItemStackTo(slot_stack, 0, 1, false)) && // smelting input
(!mergeItemStack(slot_stack, 3, 4, false)) && // fifo0 (!moveItemStackTo(slot_stack, 3, 4, false)) && // fifo0
(!mergeItemStack(slot_stack, 4, 5, false)) // fifo1 (!moveItemStackTo(slot_stack, 4, 5, false)) // fifo1
) return ItemStack.EMPTY; ) return ItemStack.EMPTY;
} else if(FurnaceTileEntity.isFuel(player_.world, slot_stack)) { } else if(FurnaceTileEntity.isFuel(player_.level, slot_stack)) {
if( if(
(!mergeItemStack(slot_stack, 1, 2, false)) && // fuel input (!moveItemStackTo(slot_stack, 1, 2, false)) && // fuel input
(!mergeItemStack(slot_stack, 5, 6, false)) && // fuel fifo0 (!moveItemStackTo(slot_stack, 5, 6, false)) && // fuel fifo0
(!mergeItemStack(slot_stack, 6, 7, false)) // fuel fifo1 (!moveItemStackTo(slot_stack, 6, 7, false)) // fuel fifo1
) return ItemStack.EMPTY; ) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index < PLAYER_INV_START_SLOTNO+27)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index < PLAYER_INV_START_SLOTNO+27)) {
// player inventory --> player hotbar // player inventory --> player hotbar
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO+27, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO+27, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO+27) && (index < PLAYER_INV_START_SLOTNO+36) && (!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+27, false))) { } else if((index >= PLAYER_INV_START_SLOTNO+27) && (index < PLAYER_INV_START_SLOTNO+36) && (!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+27, false))) {
// player hotbar --> player inventory // player hotbar --> player inventory
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
@ -868,9 +870,9 @@ public class EdFurnace
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
if(slot_stack.isEmpty()) { if(slot_stack.isEmpty()) {
slot.putStack(ItemStack.EMPTY); slot.set(ItemStack.EMPTY);
} else { } else {
slot.onSlotChanged(); slot.setChanged();
} }
if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY; if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY;
slot.onTake(player, slot_stack); slot.onTake(player, slot_stack);
@ -882,14 +884,14 @@ public class EdFurnace
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(CompoundNBT nbt) public void onGuiAction(CompoundNBT nbt)
{ Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); } { Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt); }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(String key, int value) public void onGuiAction(String key, int value)
{ {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt(key, value); nbt.putInt(key, value);
Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt);
} }
@Override @Override
@ -923,23 +925,23 @@ public class EdFurnace
{ {
renderBackground/*renderBackground*/(mx); renderBackground/*renderBackground*/(mx);
super.render(mx, mouseX, mouseY, partialTicks); super.render(mx, mouseX, mouseY, partialTicks);
renderHoveredTooltip(mx, mouseX, mouseY); renderTooltip(mx, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerForegroundLayer(MatrixStack mx, int x, int y) protected void renderLabels(MatrixStack mx, int x, int y)
{} {}
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void drawGuiContainerBackgroundLayer(MatrixStack mx, float partialTicks, int mouseX, int mouseY) protected void renderBg(MatrixStack mx, float partialTicks, int mouseX, int mouseY)
{ {
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.color3f(1.0F, 1.0F, 1.0F); RenderSystem.color3f(1.0F, 1.0F, 1.0F);
getMinecraft().getTextureManager().bindTexture(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/small_lab_furnace_gui.png")); getMinecraft().getTextureManager().bind(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/small_lab_furnace_gui.png"));
final int x0=guiLeft, y0=guiTop, w=xSize, h=ySize; final int x0=leftPos, y0=topPos, w=imageWidth, h=imageHeight;
blit(mx, x0, y0, 0, 0, w, h); blit(mx, x0, y0, 0, 0, w, h);
if(getContainer().field(4) != 0) { if(getMenu().field(4) != 0) {
final int k = flame_px(13); final int k = flame_px(13);
blit(mx, x0+59, y0+36+12-k, 176, 12-k, 14, k+1); blit(mx, x0+59, y0+36+12-k, 176, 12-k, 14, k+1);
} }
@ -948,10 +950,10 @@ public class EdFurnace
} }
private int progress_px(int pixels) private int progress_px(int pixels)
{ final int tc=getContainer().field(2), T=getContainer().field(3); return ((T>0) && (tc>0)) ? (tc * pixels / T) : (0); } { final int tc=getMenu().field(2), T=getMenu().field(3); return ((T>0) && (tc>0)) ? (tc * pixels / T) : (0); }
private int flame_px(int pixels) private int flame_px(int pixels)
{ int ibt = getContainer().field(1); return ((getContainer().field(0) * pixels) / ((ibt>0) ? (ibt) : (FurnaceTileEntity.DEFAULT_SMELTING_TIME))); } { int ibt = getMenu().field(1); return ((getMenu().field(0) * pixels) / ((ibt>0) ? (ibt) : (FurnaceTileEntity.DEFAULT_SMELTING_TIME))); }
} }
} }

View file

@ -9,9 +9,8 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import wile.engineersdecor.libmc.detail.Auxiliaries;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.block.Block; import net.minecraft.block.AbstractBlock;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.block.StainedGlassBlock; import net.minecraft.block.StainedGlassBlock;
import net.minecraft.item.DyeColor; import net.minecraft.item.DyeColor;
@ -21,18 +20,20 @@ import net.minecraft.util.text.ITextComponent;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import wile.engineersdecor.libmc.detail.Auxiliaries;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.List; import java.util.List;
public class EdGlassBlock extends StainedGlassBlock implements IDecorBlock public class EdGlassBlock extends StainedGlassBlock implements IDecorBlock
{ {
public EdGlassBlock(long config, Block.Properties properties) public EdGlassBlock(long config, AbstractBlock.Properties properties)
{ super(DyeColor.BLACK, properties); } { super(DyeColor.BLACK, properties); }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); } { Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); }
@Override @Override
@ -42,11 +43,11 @@ public class EdGlassBlock extends StainedGlassBlock implements IDecorBlock
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean isSideInvisible(BlockState state, BlockState adjacentBlockState, Direction side) public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side)
{ return (adjacentBlockState.getBlock()==this) ? true : super.isSideInvisible(state, adjacentBlockState, side); } { return (adjacentBlockState.getBlock()==this) ? true : super.skipRendering(state, adjacentBlockState, side); }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
} }

View file

@ -13,6 +13,6 @@ import net.minecraft.block.*;
public class EdGroundBlock extends DecorBlock.Normal implements IDecorBlock public class EdGroundBlock extends DecorBlock.Normal implements IDecorBlock
{ {
public EdGroundBlock(long config, Block.Properties builder) public EdGroundBlock(long config, AbstractBlock.Properties builder)
{ super(config, builder); } { super(config, builder); }
} }

View file

@ -8,6 +8,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.*; import net.minecraft.entity.*;
@ -31,19 +32,20 @@ import javax.annotation.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
public class EdHatchBlock extends DecorBlock.HorizontalWaterLoggable implements IDecorBlock public class EdHatchBlock extends DecorBlock.HorizontalWaterLoggable implements IDecorBlock
{ {
public static final BooleanProperty OPEN = BlockStateProperties.OPEN; public static final BooleanProperty OPEN = BlockStateProperties.OPEN;
public static final BooleanProperty POWERED = BlockStateProperties.POWERED; public static final BooleanProperty POWERED = BlockStateProperties.POWERED;
protected final ArrayList<VoxelShape> vshapes_open; protected final ArrayList<VoxelShape> vshapes_open;
public EdHatchBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABBClosed, final AxisAlignedBB unrotatedAABBOpen) public EdHatchBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABBClosed, final AxisAlignedBB unrotatedAABBOpen)
{ {
super(config, builder, unrotatedAABBClosed); vshapes_open = makeHorizontalShapeLookup(new AxisAlignedBB[]{unrotatedAABBOpen}); super(config, builder, unrotatedAABBClosed); vshapes_open = makeHorizontalShapeLookup(new AxisAlignedBB[]{unrotatedAABBOpen});
setDefaultState(super.getDefaultState().with(OPEN, false).with(POWERED, false)); registerDefaultState(super.defaultBlockState().setValue(OPEN, false).setValue(POWERED, false));
} }
public EdHatchBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABBsClosed, final AxisAlignedBB[] unrotatedAABBsOpen) public EdHatchBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABBsClosed, final AxisAlignedBB[] unrotatedAABBsOpen)
{ super(config, builder, unrotatedAABBsClosed); vshapes_open = makeHorizontalShapeLookup(unrotatedAABBsOpen); } { super(config, builder, unrotatedAABBsClosed); vshapes_open = makeHorizontalShapeLookup(unrotatedAABBsOpen); }
@Override @Override
@ -52,30 +54,30 @@ public class EdHatchBlock extends DecorBlock.HorizontalWaterLoggable implements
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext)
{ return state.get(OPEN) ? vshapes_open.get((state.get(HORIZONTAL_FACING)).getIndex() & 0x7) : super.getShape(state, source, pos, selectionContext); } { return state.getValue(OPEN) ? vshapes_open.get((state.getValue(HORIZONTAL_FACING)).get3DDataValue() & 0x7) : super.getShape(state, source, pos, selectionContext); }
@Override @Override
public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos) public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos)
{ return state.get(OPEN); } { return state.getValue(OPEN); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean allowsMovement(BlockState state, IBlockReader world, BlockPos pos, PathType type) public boolean isPathfindable(BlockState state, IBlockReader world, BlockPos pos, PathType type)
{ return !state.get(OPEN); } { return !state.getValue(OPEN); }
@Override @Override
public boolean isLadder(BlockState state, IWorldReader world, BlockPos pos, LivingEntity entity) public boolean isLadder(BlockState state, IWorldReader world, BlockPos pos, LivingEntity entity)
{ {
if(!state.get(OPEN)) return false; if(!state.getValue(OPEN)) return false;
{ {
final BlockState up_state = world.getBlockState(pos.up()); final BlockState up_state = world.getBlockState(pos.above());
if(up_state.isIn(this) && (up_state.get(OPEN))) return true; if(up_state.is(this) && (up_state.getValue(OPEN))) return true;
if(up_state.isLadder(world, pos.up(), entity)) return true; if(up_state.isLadder(world, pos.above(), entity)) return true;
} }
{ {
final BlockState down_state = world.getBlockState(pos.down()); final BlockState down_state = world.getBlockState(pos.below());
if(down_state.isIn(this) && (down_state.get(OPEN))) return true; if(down_state.is(this) && (down_state.getValue(OPEN))) return true;
if(down_state.isLadder(world, pos.down(), entity)) return true; if(down_state.isLadder(world, pos.below(), entity)) return true;
} }
return false; return false;
} }
@ -85,17 +87,17 @@ public class EdHatchBlock extends DecorBlock.HorizontalWaterLoggable implements
{ return false; } { return false; }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(OPEN, POWERED); } { super.createBlockStateDefinition(builder); builder.add(OPEN, POWERED); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
boolean open = !state.get(OPEN); boolean open = !state.getValue(OPEN);
world.setBlockState(pos, state.with(OPEN, open), 1|2); world.setBlock(pos, state.setValue(OPEN, open), 1|2);
world.playSound(null, pos, open?SoundEvents.BLOCK_IRON_DOOR_OPEN:SoundEvents.BLOCK_IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 0.7f, 1.4f); world.playSound(null, pos, open?SoundEvents.IRON_DOOR_OPEN:SoundEvents.IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 0.7f, 1.4f);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@ -103,11 +105,11 @@ public class EdHatchBlock extends DecorBlock.HorizontalWaterLoggable implements
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving)
{ {
if((world.isRemote) || (!(state.getBlock() instanceof EdHatchBlock))) return; if((world.isClientSide) || (!(state.getBlock() instanceof EdHatchBlock))) return;
boolean powered = world.isBlockPowered(pos); boolean powered = world.hasNeighborSignal(pos);
if(powered == state.get(POWERED)) return; if(powered == state.getValue(POWERED)) return;
if(powered != state.get(OPEN)) world.playSound(null, pos, powered?SoundEvents.BLOCK_IRON_DOOR_OPEN:SoundEvents.BLOCK_IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 0.7f, 1.4f); if(powered != state.getValue(OPEN)) world.playSound(null, pos, powered?SoundEvents.IRON_DOOR_OPEN:SoundEvents.IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 0.7f, 1.4f);
world.setBlockState(pos, state.with(OPEN, powered).with(POWERED, powered), 1|2); world.setBlock(pos, state.setValue(OPEN, powered).setValue(POWERED, powered), 1|2);
} }
@Override @Override
@ -116,17 +118,17 @@ public class EdHatchBlock extends DecorBlock.HorizontalWaterLoggable implements
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void onEntityCollision(BlockState state, World world, BlockPos pos, Entity entity) public void entityInside(BlockState state, World world, BlockPos pos, Entity entity)
{ {
if((!state.get(OPEN)) || (!(entity instanceof PlayerEntity))) return; if((!state.getValue(OPEN)) || (!(entity instanceof PlayerEntity))) return;
final PlayerEntity player = (PlayerEntity)entity; final PlayerEntity player = (PlayerEntity)entity;
if(entity.getLookVec().getY() > -0.75) return; if(entity.getLookAngle().y() > -0.75) return;
if(player.getHorizontalFacing() != state.get(HORIZONTAL_FACING)) return; if(player.getDirection() != state.getValue(HORIZONTAL_FACING)) return;
Vector3d ppos = player.getPositionVec(); Vector3d ppos = player.position();
Vector3d centre = Vector3d.copyCenteredHorizontally(pos); Vector3d centre = Vector3d.atBottomCenterOf(pos);
Vector3d v = centre.subtract(ppos); Vector3d v = centre.subtract(ppos);
if(ppos.getY() < (centre.getY()-0.1) || (v.lengthSquared() > 0.3)) return; if(ppos.y() < (centre.y()-0.1) || (v.lengthSqr() > 0.3)) return;
v = v.scale(0.3); v = v.scale(0.3);
player.addVelocity(v.x, 0, v.z); player.push(v.x, 0, v.z);
} }
} }

View file

@ -11,6 +11,7 @@ package wile.engineersdecor.blocks;
import net.minecraft.world.IWorldReader; import net.minecraft.world.IWorldReader;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
@ -62,6 +63,7 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.function.Supplier; import java.util.function.Supplier;
public class EdHopper public class EdHopper
{ {
public static void on_config() public static void on_config()
@ -73,22 +75,22 @@ public class EdHopper
public static class HopperBlock extends DecorBlock.Directed implements IDecorBlock public static class HopperBlock extends DecorBlock.Directed implements IDecorBlock
{ {
public HopperBlock(long config, Block.Properties builder, final Supplier<ArrayList<VoxelShape>> shape_supplier) public HopperBlock(long config, AbstractBlock.Properties builder, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ super(config, builder, shape_supplier); } { super(config, builder, shape_supplier); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext context) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext context)
{ return VoxelShapes.fullCube(); } { return VoxelShapes.block(); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState blockState, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState blockState, World world, BlockPos pos)
{ return Container.calcRedstone(world.getTileEntity(pos)); } { return Container.getRedstoneSignalFromBlockEntity(world.getBlockEntity(pos)); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -100,17 +102,17 @@ public class EdHopper
{ return new HopperTileEntity(); } { return new HopperTileEntity(); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
if(world.isRemote) return; if(world.isClientSide) return;
if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return; if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return;
CompoundNBT te_nbt = stack.getTag().getCompound("tedata"); CompoundNBT te_nbt = stack.getTag().getCompound("tedata");
if(te_nbt.isEmpty()) return; if(te_nbt.isEmpty()) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof HopperTileEntity)) return; if(!(te instanceof HopperTileEntity)) return;
((HopperTileEntity)te).readnbt(te_nbt, false); ((HopperTileEntity)te).readnbt(te_nbt, false);
((HopperTileEntity)te).reset_rtstate(); ((HopperTileEntity)te).reset_rtstate();
((HopperTileEntity)te).markDirty(); ((HopperTileEntity)te).setChanged();
} }
@Override @Override
@ -121,7 +123,7 @@ public class EdHopper
public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof HopperTileEntity)) return stacks; if(!(te instanceof HopperTileEntity)) return stacks;
if(!explosion) { if(!explosion) {
ItemStack stack = new ItemStack(this, 1); ItemStack stack = new ItemStack(this, 1);
@ -143,10 +145,10 @@ public class EdHopper
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof HopperTileEntity)) return ActionResultType.FAIL; if(!(te instanceof HopperTileEntity)) return ActionResultType.FAIL;
if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL; if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL;
NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te); NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te);
@ -157,18 +159,18 @@ public class EdHopper
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused)
{ {
if(!(world instanceof World) || (((World) world).isRemote)) return; if(!(world instanceof World) || (((World) world).isClientSide)) return;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof HopperTileEntity)) return; if(!(te instanceof HopperTileEntity)) return;
((HopperTileEntity)te).block_updated(); ((HopperTileEntity)te).block_updated();
} }
@Override @Override
public void onFallenUpon(World world, BlockPos pos, Entity entity, float fallDistance) public void fallOn(World world, BlockPos pos, Entity entity, float fallDistance)
{ {
super.onFallenUpon(world, pos, entity, fallDistance); super.fallOn(world, pos, entity, fallDistance);
if(!(entity instanceof ItemEntity)) return; if(!(entity instanceof ItemEntity)) return;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof HopperTileEntity)) return; if(!(te instanceof HopperTileEntity)) return;
((HopperTileEntity)te).collection_timer_ = 0; ((HopperTileEntity)te).collection_timer_ = 0;
} }
@ -179,17 +181,17 @@ public class EdHopper
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean canProvidePower(BlockState state) public boolean isSignalSource(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getWeakPower(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side) public int getSignal(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side)
{ return 0; } { return 0; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getStrongPower(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side) public int getDirectSignal(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side)
{ return 0; } { return 0; }
} }
@ -285,7 +287,7 @@ public class EdHopper
public void block_updated() public void block_updated()
{ {
// RS power check, both edges // RS power check, both edges
boolean powered = world.isBlockPowered(pos); boolean powered = level.hasNeighborSignal(worldPosition);
if(block_power_signal_ != powered) block_power_updated_ = true; if(block_power_signal_ != powered) block_power_updated_ = true;
block_power_signal_ = powered; block_power_signal_ = powered;
tick_timer_ = 1; tick_timer_ = 1;
@ -297,17 +299,17 @@ public class EdHopper
// TileEntity -------------------------------------------------------------------------------------------- // TileEntity --------------------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt, false); } { super.load(state, nbt); readnbt(nbt, false); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt, false); return nbt; } { super.save(nbt); writenbt(nbt, false); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
Arrays.stream(item_handlers).forEach(LazyOptional::invalidate); Arrays.stream(item_handlers).forEach(LazyOptional::invalidate);
} }
@ -315,7 +317,7 @@ public class EdHopper
@Override @Override
public ITextComponent getName() public ITextComponent getName()
{ final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getTranslationKey() : "Factory Hopper"); } { final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getDescriptionId() : "Factory Hopper"); }
@Override @Override
public boolean hasCustomName() public boolean hasCustomName()
@ -333,12 +335,12 @@ public class EdHopper
@Override @Override
public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player ) public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player )
{ return new HopperContainer(id, inventory, this, IWorldPosCallable.of(world, pos), fields); } { return new HopperContainer(id, inventory, this, IWorldPosCallable.create(level, worldPosition), fields); }
// IInventory -------------------------------------------------------------------------------------------- // IInventory --------------------------------------------------------------------------------------------
@Override @Override
public int getSizeInventory() public int getContainerSize()
{ return stacks_.size(); } { return stacks_.size(); }
@Override @Override
@ -346,52 +348,52 @@ public class EdHopper
{ for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; } { for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; }
@Override @Override
public ItemStack getStackInSlot(int index) public ItemStack getItem(int index)
{ return (index < stacks_.size()) ? stacks_.get(index) : ItemStack.EMPTY; } { return (index < stacks_.size()) ? stacks_.get(index) : ItemStack.EMPTY; }
@Override @Override
public ItemStack decrStackSize(int index, int count) public ItemStack removeItem(int index, int count)
{ return ItemStackHelper.getAndSplit(stacks_, index, count); } { return ItemStackHelper.removeItem(stacks_, index, count); }
@Override @Override
public ItemStack removeStackFromSlot(int index) public ItemStack removeItemNoUpdate(int index)
{ return ItemStackHelper.getAndRemove(stacks_, index); } { return ItemStackHelper.takeItem(stacks_, index); }
@Override @Override
public void setInventorySlotContents(int index, ItemStack stack) public void setItem(int index, ItemStack stack)
{ {
stacks_.set(index, stack); stacks_.set(index, stack);
if(stack.getCount() > getInventoryStackLimit()) stack.setCount(getInventoryStackLimit()); if(stack.getCount() > getMaxStackSize()) stack.setCount(getMaxStackSize());
if(tick_timer_ > 8) tick_timer_ = 8; if(tick_timer_ > 8) tick_timer_ = 8;
markDirty(); setChanged();
} }
@Override @Override
public int getInventoryStackLimit() public int getMaxStackSize()
{ return 64; } { return 64; }
@Override @Override
public void markDirty() public void setChanged()
{ super.markDirty(); } { super.setChanged(); }
@Override @Override
public boolean isUsableByPlayer(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return ((getWorld().getTileEntity(getPos()) == this)) && (getPos().distanceSq(player.getPosition()) < 64); } { return ((getLevel().getBlockEntity(getBlockPos()) == this)) && (getBlockPos().distSqr(player.blockPosition()) < 64); }
@Override @Override
public void openInventory(PlayerEntity player) public void startOpen(PlayerEntity player)
{} {}
@Override @Override
public void closeInventory(PlayerEntity player) public void stopOpen(PlayerEntity player)
{ markDirty(); } { setChanged(); }
@Override @Override
public boolean isItemValidForSlot(int index, ItemStack stack) public boolean canPlaceItem(int index, ItemStack stack)
{ return true; } { return true; }
@Override @Override
public void clear() public void clearContent()
{ stacks_.clear(); } { stacks_.clear(); }
// Fields ----------------------------------------------------------------------------------------------- // Fields -----------------------------------------------------------------------------------------------
@ -442,11 +444,11 @@ public class EdHopper
{ return SIDED_INV_SLOTS; } { return SIDED_INV_SLOTS; }
@Override @Override
public boolean canInsertItem(int index, ItemStack stack, Direction direction) public boolean canPlaceItemThroughFace(int index, ItemStack stack, Direction direction)
{ return is_input_slot(index) && isItemValidForSlot(index, stack); } { return is_input_slot(index) && canPlaceItem(index, stack); }
@Override @Override
public boolean canExtractItem(int index, ItemStack stack, Direction direction) public boolean canTakeItemThroughFace(int index, ItemStack stack, Direction direction)
{ return (direction != Direction.UP); } { return (direction != Direction.UP); }
// Capability export ------------------------------------------------------------------------------------ // Capability export ------------------------------------------------------------------------------------
@ -462,7 +464,7 @@ public class EdHopper
private IItemHandler inventory_entity_handler(BlockPos where) private IItemHandler inventory_entity_handler(BlockPos where)
{ {
final List<Entity> entities = world.getEntitiesInAABBexcluding(null, (new AxisAlignedBB(where)), EntityPredicates.HAS_INVENTORY); final List<Entity> entities = level.getEntities((Entity)null, (new AxisAlignedBB(where)), EntityPredicates.CONTAINER_ENTITY_SELECTOR);
return entities.isEmpty() ? null : Inventories.itemhandler(entities.get(0)); return entities.isEmpty() ? null : Inventories.itemhandler(entities.get(0));
} }
@ -512,19 +514,19 @@ public class EdHopper
current_slot_index_ = 0; current_slot_index_ = 0;
return false; return false;
} }
final BlockPos facing_pos = pos.offset(facing); final BlockPos facing_pos = worldPosition.relative(facing);
IItemHandler ih = null; IItemHandler ih = null;
// Tile entity insertion check // Tile entity insertion check
{ {
final TileEntity te = world.getTileEntity(facing_pos); final TileEntity te = level.getBlockEntity(facing_pos);
if(te != null) { if(te != null) {
ih = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite()).orElse(null); ih = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite()).orElse(null);
if(ih == null) { delay_timer_ = TICK_INTERVAL+2; return false; } if(ih == null) { delay_timer_ = TICK_INTERVAL+2; return false; }
if(te instanceof net.minecraft.tileentity.HopperTileEntity) { if(te instanceof net.minecraft.tileentity.HopperTileEntity) {
Direction f = world.getBlockState(facing_pos).get(net.minecraft.block.HopperBlock.FACING); Direction f = level.getBlockState(facing_pos).getValue(net.minecraft.block.HopperBlock.FACING);
if(f==facing.getOpposite()) return false; // no back transfer if(f==facing.getOpposite()) return false; // no back transfer
} else if(te instanceof EdHopper.HopperTileEntity) { } else if(te instanceof EdHopper.HopperTileEntity) {
Direction f = world.getBlockState(facing_pos).get(EdHopper.HopperBlock.FACING); Direction f = level.getBlockState(facing_pos).getValue(EdHopper.HopperBlock.FACING);
if(f==facing.getOpposite()) return false; if(f==facing.getOpposite()) return false;
} }
} }
@ -582,22 +584,22 @@ public class EdHopper
private boolean try_inventory_extract(final IInventory inv) private boolean try_inventory_extract(final IInventory inv)
{ {
final int end = inv.getSizeInventory(); final int end = inv.getContainerSize();
int n_to_extract = transfer_count_; int n_to_extract = transfer_count_;
for(int i=0; i<end; ++i) { for(int i=0; i<end; ++i) {
ItemStack stack = inv.getStackInSlot(i).copy(); ItemStack stack = inv.getItem(i).copy();
if(stack.isEmpty()) continue; if(stack.isEmpty()) continue;
int n_accepted = try_insert_into_hopper(stack); int n_accepted = try_insert_into_hopper(stack);
if(n_accepted > 0) { if(n_accepted > 0) {
stack.shrink(n_accepted); stack.shrink(n_accepted);
n_to_extract -= n_accepted; n_to_extract -= n_accepted;
if(stack.isEmpty()) stack = ItemStack.EMPTY; if(stack.isEmpty()) stack = ItemStack.EMPTY;
inv.setInventorySlotContents(i, stack); inv.setItem(i, stack);
if(n_to_extract <= 0) break; if(n_to_extract <= 0) break;
} }
} }
if(n_to_extract < transfer_count_) { if(n_to_extract < transfer_count_) {
inv.markDirty(); inv.setChanged();
return true; return true;
} else { } else {
return false; return false;
@ -609,19 +611,19 @@ public class EdHopper
AxisAlignedBB collection_volume; AxisAlignedBB collection_volume;
Vector3d rpos; Vector3d rpos;
if(facing==Direction.UP) { if(facing==Direction.UP) {
rpos = new Vector3d(0.5+pos.getX(),1.5+pos.getY(),0.5+pos.getZ()); rpos = new Vector3d(0.5+worldPosition.getX(),1.5+worldPosition.getY(),0.5+worldPosition.getZ());
collection_volume = (new AxisAlignedBB(pos.up())).grow(0.1+collection_range_, 0.6, 0.1+collection_range_); collection_volume = (new AxisAlignedBB(worldPosition.above())).inflate(0.1+collection_range_, 0.6, 0.1+collection_range_);
} else { } else {
rpos = new Vector3d(0.5+pos.getX(),-1.5+pos.getY(),0.5+pos.getZ()); rpos = new Vector3d(0.5+worldPosition.getX(),-1.5+worldPosition.getY(),0.5+worldPosition.getZ());
collection_volume = (new AxisAlignedBB(pos.down(2))).grow(0.1+collection_range_, 1, 0.1+collection_range_); collection_volume = (new AxisAlignedBB(worldPosition.below(2))).inflate(0.1+collection_range_, 1, 0.1+collection_range_);
} }
final List<ItemEntity> items = world.getEntitiesWithinAABB(ItemEntity.class, collection_volume, e->(e.isAlive() && e.isOnGround())); final List<ItemEntity> items = level.getEntitiesOfClass(ItemEntity.class, collection_volume, e->(e.isAlive() && e.isOnGround()));
if(items.size() <= 0) return false; if(items.size() <= 0) return false;
final int max_to_collect = 3; final int max_to_collect = 3;
int n_collected = 0; int n_collected = 0;
for(ItemEntity ie:items) { for(ItemEntity ie:items) {
boolean is_direct_collection_tange = ie.getDistanceSq(rpos)<0.7; boolean is_direct_collection_tange = ie.distanceToSqr(rpos)<0.7;
if(!is_direct_collection_tange && (ie.cannotPickup())) continue; if(!is_direct_collection_tange && (ie.hasPickUpDelay())) continue;
ItemStack stack = ie.getItem(); ItemStack stack = ie.getItem();
if(stack.isEmpty()) continue; if(stack.isEmpty()) continue;
int n_accepted = try_insert_into_hopper(stack); int n_accepted = try_insert_into_hopper(stack);
@ -643,8 +645,8 @@ public class EdHopper
public void tick() public void tick()
{ {
// Tick cycle pre-conditions // Tick cycle pre-conditions
if(world.isRemote) return; if(level.isClientSide) return;
if((delay_timer_ > 0) && ((--delay_timer_) == 0)) markDirty(); if((delay_timer_ > 0) && ((--delay_timer_) == 0)) setChanged();
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
// Cycle init // Cycle init
@ -652,12 +654,12 @@ public class EdHopper
final boolean rssignal = ((logic_ & LOGIC_IGNORE_EXT)!=0) || ((logic_ & LOGIC_INVERTED)!=0)==(!block_power_signal_); final boolean rssignal = ((logic_ & LOGIC_IGNORE_EXT)!=0) || ((logic_ & LOGIC_INVERTED)!=0)==(!block_power_signal_);
final boolean pulse_mode = ((logic_ & (LOGIC_CONTINUOUS|LOGIC_IGNORE_EXT))==0); final boolean pulse_mode = ((logic_ & (LOGIC_CONTINUOUS|LOGIC_IGNORE_EXT))==0);
boolean trigger = ((logic_ & LOGIC_IGNORE_EXT)!=0) || (rssignal && ((block_power_updated_) || (!pulse_mode))); boolean trigger = ((logic_ & LOGIC_IGNORE_EXT)!=0) || (rssignal && ((block_power_updated_) || (!pulse_mode)));
final BlockState state = world.getBlockState(pos); final BlockState state = level.getBlockState(worldPosition);
if(!(state.getBlock() instanceof HopperBlock)) { block_power_signal_= false; return; } if(!(state.getBlock() instanceof HopperBlock)) { block_power_signal_= false; return; }
final Direction hopper_facing = state.get(HopperBlock.FACING); final Direction hopper_facing = state.getValue(HopperBlock.FACING);
// Trigger edge detection for next cycle // Trigger edge detection for next cycle
{ {
boolean tr = world.isBlockPowered(pos); boolean tr = level.hasNeighborSignal(worldPosition);
block_power_updated_ = (block_power_signal_ != tr); block_power_updated_ = (block_power_signal_ != tr);
block_power_signal_ = tr; block_power_signal_ = tr;
if(block_power_updated_) dirty = true; if(block_power_updated_) dirty = true;
@ -665,7 +667,7 @@ public class EdHopper
// Collection // Collection
if(rssignal || pulse_mode) { if(rssignal || pulse_mode) {
Direction hopper_input_facing = (hopper_facing==Direction.UP) ? Direction.DOWN : Direction.UP; Direction hopper_input_facing = (hopper_facing==Direction.UP) ? Direction.DOWN : Direction.UP;
TileEntity te = world.getTileEntity(pos.offset(hopper_input_facing)); TileEntity te = level.getBlockEntity(worldPosition.relative(hopper_input_facing));
IItemHandler ih = (te==null) ? (null) : (te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, hopper_input_facing.getOpposite()).orElse(null)); IItemHandler ih = (te==null) ? (null) : (te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, hopper_input_facing.getOpposite()).orElse(null));
if((ih != null) || (te instanceof ISidedInventory)) { if((ih != null) || (te instanceof ISidedInventory)) {
// Tile Entity pulling // Tile Entity pulling
@ -676,7 +678,7 @@ public class EdHopper
} }
} }
if(ih==null) { if(ih==null) {
ih = inventory_entity_handler(pos.offset(hopper_input_facing)); ih = inventory_entity_handler(worldPosition.relative(hopper_input_facing));
if((ih!=null) && (try_item_handler_extract(ih))) dirty = true; if((ih!=null) && (try_item_handler_extract(ih))) dirty = true;
} }
if((ih==null) && (collection_timer_ -= TICK_INTERVAL) <= 0) { if((ih==null) && (collection_timer_ -= TICK_INTERVAL) <= 0) {
@ -690,7 +692,7 @@ public class EdHopper
delay_timer_ = PERIOD_OFFSET + transfer_period_ * 2; delay_timer_ = PERIOD_OFFSET + transfer_period_ * 2;
if(try_insert(hopper_facing)) dirty = true; if(try_insert(hopper_facing)) dirty = true;
} }
if(dirty) markDirty(); if(dirty) setChanged();
if(trigger && (tick_timer_ > TICK_INTERVAL)) tick_timer_ = TICK_INTERVAL; if(trigger && (tick_timer_ > TICK_INTERVAL)) tick_timer_ = TICK_INTERVAL;
} }
} }
@ -718,7 +720,7 @@ public class EdHopper
public final int field(int index) { return fields_.get(index); } public final int field(int index) { return fields_.get(index); }
public HopperContainer(int cid, PlayerInventory player_inventory) public HopperContainer(int cid, PlayerInventory player_inventory)
{ this(cid, player_inventory, new Inventory(HopperTileEntity.NUM_OF_SLOTS), IWorldPosCallable.DUMMY, new IntArray(HopperTileEntity.NUM_OF_FIELDS)); } { this(cid, player_inventory, new Inventory(HopperTileEntity.NUM_OF_SLOTS), IWorldPosCallable.NULL, new IntArray(HopperTileEntity.NUM_OF_FIELDS)); }
private HopperContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields) private HopperContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields)
{ {
@ -746,34 +748,34 @@ public class EdHopper
addSlot(new Slot(player_inventory, x+y*9+9, 8+x*18, 71+y*18)); // player slots: 9..35 addSlot(new Slot(player_inventory, x+y*9+9, 8+x*18, 71+y*18)); // player slots: 9..35
} }
} }
this.trackIntArray(fields_); // === Add reference holders this.addDataSlots(fields_); // === Add reference holders
} }
@Override @Override
public boolean canInteractWith(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return inventory_.isUsableByPlayer(player); } { return inventory_.stillValid(player); }
@Override @Override
public ItemStack transferStackInSlot(PlayerEntity player, int index) public ItemStack quickMoveStack(PlayerEntity player, int index)
{ {
Slot slot = getSlot(index); Slot slot = getSlot(index);
if((slot==null) || (!slot.getHasStack())) return ItemStack.EMPTY; if((slot==null) || (!slot.hasItem())) return ItemStack.EMPTY;
ItemStack slot_stack = slot.getStack(); ItemStack slot_stack = slot.getItem();
ItemStack transferred = slot_stack.copy(); ItemStack transferred = slot_stack.copy();
if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) { if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) {
// Device slots // Device slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) {
// Player slot // Player slot
if(!mergeItemStack(slot_stack, 0, HopperTileEntity.NUM_OF_SLOTS, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, 0, HopperTileEntity.NUM_OF_SLOTS, false)) return ItemStack.EMPTY;
} else { } else {
// invalid slot // invalid slot
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
if(slot_stack.isEmpty()) { if(slot_stack.isEmpty()) {
slot.putStack(ItemStack.EMPTY); slot.set(ItemStack.EMPTY);
} else { } else {
slot.onSlotChanged(); slot.setChanged();
} }
if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY; if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY;
slot.onTake(player, slot_stack); slot.onTake(player, slot_stack);
@ -784,21 +786,21 @@ public class EdHopper
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(CompoundNBT nbt) public void onGuiAction(CompoundNBT nbt)
{ Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); } { Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt); }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(String key, int value) public void onGuiAction(String key, int value)
{ {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt(key, value); nbt.putInt(key, value);
Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt);
} }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(String message, CompoundNBT nbt) public void onGuiAction(String message, CompoundNBT nbt)
{ {
nbt.putString("action", message); nbt.putString("action", message);
Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt);
} }
@Override @Override
@ -820,20 +822,20 @@ public class EdHopper
final int slotId = nbt.contains("slot") ? nbt.getInt("slot") : -1; final int slotId = nbt.contains("slot") ? nbt.getInt("slot") : -1;
switch(nbt.getString("action")) { switch(nbt.getString("action")) {
case QUICK_MOVE_ALL: { case QUICK_MOVE_ALL: {
if((slotId >= STORAGE_SLOT_BEGIN) && (slotId < STORAGE_SLOT_END) && (getSlot(slotId).getHasStack())) { if((slotId >= STORAGE_SLOT_BEGIN) && (slotId < STORAGE_SLOT_END) && (getSlot(slotId).hasItem())) {
changed = block_storage_range_.move(getSlot(slotId).getSlotIndex(), player_inventory_range_, true, false, true, true); changed = block_storage_range_.move(getSlot(slotId).getSlotIndex(), player_inventory_range_, true, false, true, true);
} else if((slotId >= PLAYER_SLOT_BEGIN) && (slotId < PLAYER_SLOT_END) && (getSlot(slotId).getHasStack())) { } else if((slotId >= PLAYER_SLOT_BEGIN) && (slotId < PLAYER_SLOT_END) && (getSlot(slotId).hasItem())) {
changed = player_inventory_range_.move(getSlot(slotId).getSlotIndex(), block_storage_range_, true, false, false, true); changed = player_inventory_range_.move(getSlot(slotId).getSlotIndex(), block_storage_range_, true, false, false, true);
} }
} break; } break;
} }
if(changed) { if(changed) {
inventory_.markDirty(); inventory_.setChanged();
player.inventory.markDirty(); player.inventory.setChanged();
detectAndSendChanges(); broadcastChanges();
} }
} }
te.markDirty(); te.setChanged();
} }
} }
@ -855,7 +857,7 @@ public class EdHopper
{ {
super.init(); super.init();
{ {
final String prefix = ModContent.FACTORY_HOPPER.getTranslationKey() + ".tooltips."; final String prefix = ModContent.FACTORY_HOPPER.getDescriptionId() + ".tooltips.";
final int x0 = getGuiLeft(), y0 = getGuiTop(); final int x0 = getGuiLeft(), y0 = getGuiTop();
tooltip_.init( tooltip_.init(
new TipRange(x0+148, y0+22, 3, 3, new TranslationTextComponent(prefix + "delayindicator")), new TipRange(x0+148, y0+22, 3, 3, new TranslationTextComponent(prefix + "delayindicator")),
@ -874,23 +876,23 @@ public class EdHopper
{ {
renderBackground(mx); renderBackground(mx);
super.render(mx, mouseX, mouseY, partialTicks); super.render(mx, mouseX, mouseY, partialTicks);
if(!tooltip_.render(mx, this, mouseX, mouseY)) renderHoveredTooltip(mx, mouseX, mouseY); if(!tooltip_.render(mx, this, mouseX, mouseY)) renderTooltip(mx, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerForegroundLayer(MatrixStack mx, int x, int y) protected void renderLabels(MatrixStack mx, int x, int y)
{} {}
@Override @Override
protected void handleMouseClick(Slot slot, int slotId, int button, ClickType type) protected void slotClicked(Slot slot, int slotId, int button, ClickType type)
{ {
tooltip_.resetTimer(); tooltip_.resetTimer();
if((type == ClickType.QUICK_MOVE) && (slot!=null) && slot.getHasStack() && Auxiliaries.isShiftDown() && Auxiliaries.isCtrlDown()) { if((type == ClickType.QUICK_MOVE) && (slot!=null) && slot.hasItem() && Auxiliaries.isShiftDown() && Auxiliaries.isCtrlDown()) {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt("slot", slotId); nbt.putInt("slot", slotId);
container.onGuiAction(HopperContainer.QUICK_MOVE_ALL, nbt); menu.onGuiAction(HopperContainer.QUICK_MOVE_ALL, nbt);
} else { } else {
super.handleMouseClick(slot, slotId, button, type); super.slotClicked(slot, slotId, button, type);
} }
} }
@ -898,11 +900,11 @@ public class EdHopper
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) public boolean mouseClicked(double mouseX, double mouseY, int mouseButton)
{ {
tooltip_.resetTimer(); tooltip_.resetTimer();
HopperContainer container = (HopperContainer)getContainer(); HopperContainer container = (HopperContainer)getMenu();
int mx = (int)(mouseX - getGuiLeft() + .5), my = (int)(mouseY - getGuiTop() + .5); int mx = (int)(mouseX - getGuiLeft() + .5), my = (int)(mouseY - getGuiTop() + .5);
if((!isPointInRegion(126, 1, 49, 60, mouseX, mouseY))) { if((!isHovering(126, 1, 49, 60, mouseX, mouseY))) {
return super.mouseClicked(mouseX, mouseY, mouseButton); return super.mouseClicked(mouseX, mouseY, mouseButton);
} else if(isPointInRegion(128, 9, 44, 10, mouseX, mouseY)) { } else if(isHovering(128, 9, 44, 10, mouseX, mouseY)) {
int range = (mx-133); int range = (mx-133);
if(range < -1) { if(range < -1) {
range = container.field(0) - 1; // - range = container.field(0) - 1; // -
@ -913,7 +915,7 @@ public class EdHopper
range = MathHelper.clamp(range, 0, HopperTileEntity.MAX_COLLECTION_RANGE); range = MathHelper.clamp(range, 0, HopperTileEntity.MAX_COLLECTION_RANGE);
} }
container.onGuiAction("range", range); container.onGuiAction("range", range);
} else if(isPointInRegion(128, 21, 44, 10, mouseX, mouseY)) { } else if(isHovering(128, 21, 44, 10, mouseX, mouseY)) {
int period = (mx-133); int period = (mx-133);
if(period < -1) { if(period < -1) {
period = container.field(3) - 3; // - period = container.field(3) - 3; // -
@ -924,7 +926,7 @@ public class EdHopper
} }
period = MathHelper.clamp(period, 0, 100); period = MathHelper.clamp(period, 0, 100);
container.onGuiAction("period", period); container.onGuiAction("period", period);
} else if(isPointInRegion(128, 34, 44, 10, mouseX, mouseY)) { } else if(isHovering(128, 34, 44, 10, mouseX, mouseY)) {
int ndrop = (mx-134); int ndrop = (mx-134);
if(ndrop < -1) { if(ndrop < -1) {
ndrop = container.field(1) - 1; // - ndrop = container.field(1) - 1; // -
@ -934,9 +936,9 @@ public class EdHopper
ndrop = MathHelper.clamp(1+ndrop, 1, HopperTileEntity.MAX_TRANSFER_COUNT); // slider ndrop = MathHelper.clamp(1+ndrop, 1, HopperTileEntity.MAX_TRANSFER_COUNT); // slider
} }
container.onGuiAction("xsize", ndrop); container.onGuiAction("xsize", ndrop);
} else if(isPointInRegion(133, 49, 9, 9, mouseX, mouseY)) { } else if(isHovering(133, 49, 9, 9, mouseX, mouseY)) {
container.onGuiAction("manual_trigger", 1); container.onGuiAction("manual_trigger", 1);
} else if(isPointInRegion(145, 49, 9, 9, mouseX, mouseY)) { } else if(isHovering(145, 49, 9, 9, mouseX, mouseY)) {
final int mask = (HopperTileEntity.LOGIC_INVERTED|HopperTileEntity.LOGIC_IGNORE_EXT|HopperTileEntity.LOGIC_NOT_INVERTED); final int mask = (HopperTileEntity.LOGIC_INVERTED|HopperTileEntity.LOGIC_IGNORE_EXT|HopperTileEntity.LOGIC_NOT_INVERTED);
int logic = (container.field(2) & mask); int logic = (container.field(2) & mask);
switch(logic) { switch(logic) {
@ -946,7 +948,7 @@ public class EdHopper
default: logic = HopperTileEntity.LOGIC_IGNORE_EXT; default: logic = HopperTileEntity.LOGIC_IGNORE_EXT;
} }
container.onGuiAction("logic", (container.field(2) & (~mask)) | logic); container.onGuiAction("logic", (container.field(2) & (~mask)) | logic);
} else if(isPointInRegion(159, 49, 7, 9, mouseX, mouseY)) { } else if(isHovering(159, 49, 7, 9, mouseX, mouseY)) {
container.onGuiAction("logic", container.field(2) ^ HopperTileEntity.LOGIC_CONTINUOUS); container.onGuiAction("logic", container.field(2) ^ HopperTileEntity.LOGIC_CONTINUOUS);
} }
return true; return true;
@ -954,14 +956,14 @@ public class EdHopper
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void drawGuiContainerBackgroundLayer(MatrixStack mx, float partialTicks, int mouseX, int mouseY) protected void renderBg(MatrixStack mx, float partialTicks, int mouseX, int mouseY)
{ {
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
getMinecraft().getTextureManager().bindTexture(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/factory_hopper_gui.png")); getMinecraft().getTextureManager().bind(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/factory_hopper_gui.png"));
final int x0=getGuiLeft(), y0=getGuiTop(), w=getXSize(), h=getYSize(); final int x0=getGuiLeft(), y0=getGuiTop(), w=getXSize(), h=getYSize();
blit(mx, x0, y0, 0, 0, w, h); blit(mx, x0, y0, 0, 0, w, h);
HopperContainer container = (HopperContainer)getContainer(); HopperContainer container = (HopperContainer)getMenu();
// active slot // active slot
{ {
int slot_index = container.field(6); int slot_index = container.field(6);

View file

@ -9,6 +9,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.entity.EntitySpawnPlacementRegistry; import net.minecraft.entity.EntitySpawnPlacementRegistry;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
@ -40,6 +41,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class EdHorizontalSupportBlock extends DecorBlock.WaterLoggable implements IDecorBlock public class EdHorizontalSupportBlock extends DecorBlock.WaterLoggable implements IDecorBlock
{ {
public static final BooleanProperty EASTWEST = BooleanProperty.create("eastwest"); public static final BooleanProperty EASTWEST = BooleanProperty.create("eastwest");
@ -48,22 +50,22 @@ public class EdHorizontalSupportBlock extends DecorBlock.WaterLoggable implement
public static final IntegerProperty DOWNCONNECT = IntegerProperty.create("downconnect", 0, 2); public static final IntegerProperty DOWNCONNECT = IntegerProperty.create("downconnect", 0, 2);
protected final Map<BlockState, VoxelShape> AABBs; protected final Map<BlockState, VoxelShape> AABBs;
public EdHorizontalSupportBlock(long config, Block.Properties builder, final AxisAlignedBB mainBeamAABB, final AxisAlignedBB eastBeamAABB, final AxisAlignedBB thinDownBeamAABB, final AxisAlignedBB thickDownBeamAABB) public EdHorizontalSupportBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB mainBeamAABB, final AxisAlignedBB eastBeamAABB, final AxisAlignedBB thinDownBeamAABB, final AxisAlignedBB thickDownBeamAABB)
{ {
super(config|DecorBlock.CFG_HORIZIONTAL, builder); super(config|DecorBlock.CFG_HORIZIONTAL, builder);
Map<BlockState, VoxelShape> aabbs = new HashMap<>(); Map<BlockState, VoxelShape> aabbs = new HashMap<>();
for(boolean eastwest:EASTWEST.getAllowedValues()) { for(boolean eastwest:EASTWEST.getPossibleValues()) {
for(boolean leftbeam:LEFTBEAM.getAllowedValues()) { for(boolean leftbeam:LEFTBEAM.getPossibleValues()) {
for(boolean rightbeam:RIGHTBEAM.getAllowedValues()) { for(boolean rightbeam:RIGHTBEAM.getPossibleValues()) {
for(int downconnect:DOWNCONNECT.getAllowedValues()) { for(int downconnect:DOWNCONNECT.getPossibleValues()) {
final BlockState state = getDefaultState().with(EASTWEST, eastwest).with(LEFTBEAM, leftbeam).with(RIGHTBEAM, rightbeam).with(DOWNCONNECT, downconnect); final BlockState state = defaultBlockState().setValue(EASTWEST, eastwest).setValue(LEFTBEAM, leftbeam).setValue(RIGHTBEAM, rightbeam).setValue(DOWNCONNECT, downconnect);
VoxelShape shape = VoxelShapes.create(Auxiliaries.getRotatedAABB(mainBeamAABB, eastwest?Direction.EAST:Direction.NORTH, true)); VoxelShape shape = VoxelShapes.create(Auxiliaries.getRotatedAABB(mainBeamAABB, eastwest?Direction.EAST:Direction.NORTH, true));
if(rightbeam) shape = VoxelShapes.combine(shape, VoxelShapes.create(Auxiliaries.getRotatedAABB(eastBeamAABB, eastwest?Direction.EAST:Direction.NORTH, true)), IBooleanFunction.OR); if(rightbeam) shape = VoxelShapes.joinUnoptimized(shape, VoxelShapes.create(Auxiliaries.getRotatedAABB(eastBeamAABB, eastwest?Direction.EAST:Direction.NORTH, true)), IBooleanFunction.OR);
if(leftbeam) shape = VoxelShapes.combine(shape, VoxelShapes.create(Auxiliaries.getRotatedAABB(eastBeamAABB, eastwest?Direction.WEST:Direction.SOUTH, true)), IBooleanFunction.OR); if(leftbeam) shape = VoxelShapes.joinUnoptimized(shape, VoxelShapes.create(Auxiliaries.getRotatedAABB(eastBeamAABB, eastwest?Direction.WEST:Direction.SOUTH, true)), IBooleanFunction.OR);
if(downconnect==1) shape = VoxelShapes.combine(shape, VoxelShapes.create(thinDownBeamAABB), IBooleanFunction.OR); if(downconnect==1) shape = VoxelShapes.joinUnoptimized(shape, VoxelShapes.create(thinDownBeamAABB), IBooleanFunction.OR);
if(downconnect==2) shape = VoxelShapes.combine(shape, VoxelShapes.create(thickDownBeamAABB), IBooleanFunction.OR); if(downconnect==2) shape = VoxelShapes.joinUnoptimized(shape, VoxelShapes.create(thickDownBeamAABB), IBooleanFunction.OR);
aabbs.put(state.with(WATERLOGGED, false), shape); aabbs.put(state.setValue(WATERLOGGED, false), shape);
aabbs.put(state.with(WATERLOGGED, true), shape); aabbs.put(state.setValue(WATERLOGGED, true), shape);
} }
} }
} }
@ -76,7 +78,7 @@ public class EdHorizontalSupportBlock extends DecorBlock.WaterLoggable implement
{ return RenderTypeHint.CUTOUT; } { return RenderTypeHint.CUTOUT; }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@ -92,23 +94,23 @@ public class EdHorizontalSupportBlock extends DecorBlock.WaterLoggable implement
{ return getShape(state, world, pos, selectionContext); } { return getShape(state, world, pos, selectionContext); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(EASTWEST, RIGHTBEAM, LEFTBEAM, DOWNCONNECT); } { super.createBlockStateDefinition(builder); builder.add(EASTWEST, RIGHTBEAM, LEFTBEAM, DOWNCONNECT); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return temp_block_update_until_better(super.getStateForPlacement(context).with(EASTWEST, context.getPlacementHorizontalFacing().getAxis()==Direction.Axis.X), context.getWorld(), context.getPos()); } { return temp_block_update_until_better(super.getStateForPlacement(context).setValue(EASTWEST, context.getHorizontalDirection().getAxis()==Direction.Axis.X), context.getLevel(), context.getClickedPos()); }
private BlockState temp_block_update_until_better(BlockState state, IWorld world, BlockPos pos) private BlockState temp_block_update_until_better(BlockState state, IWorld world, BlockPos pos)
{ {
boolean ew = state.get(EASTWEST); boolean ew = state.getValue(EASTWEST);
final BlockState rstate = world.getBlockState((!ew) ? (pos.east()) : (pos.south()) ); final BlockState rstate = world.getBlockState((!ew) ? (pos.east()) : (pos.south()) );
final BlockState lstate = world.getBlockState((!ew) ? (pos.west()) : (pos.north()) ); final BlockState lstate = world.getBlockState((!ew) ? (pos.west()) : (pos.north()) );
final BlockState dstate = world.getBlockState(pos.down()); final BlockState dstate = world.getBlockState(pos.below());
int down_connector = 0; int down_connector = 0;
if((dstate.getBlock() instanceof EdStraightPoleBlock)) { if((dstate.getBlock() instanceof EdStraightPoleBlock)) {
final Direction dfacing = dstate.get(EdStraightPoleBlock.FACING); final Direction dfacing = dstate.getValue(EdStraightPoleBlock.FACING);
final EdStraightPoleBlock pole = (EdStraightPoleBlock)dstate.getBlock(); final EdStraightPoleBlock pole = (EdStraightPoleBlock)dstate.getBlock();
if((dfacing.getAxis() == Direction.Axis.Y)) { if((dfacing.getAxis() == Direction.Axis.Y)) {
if((pole== ModContent.THICK_STEEL_POLE) || ((pole==ModContent.THICK_STEEL_POLE_HEAD) && (dfacing==Direction.UP))) { if((pole== ModContent.THICK_STEEL_POLE) || ((pole==ModContent.THICK_STEEL_POLE_HEAD) && (dfacing==Direction.UP))) {
@ -118,43 +120,43 @@ public class EdHorizontalSupportBlock extends DecorBlock.WaterLoggable implement
} }
} }
} }
return state.with(RIGHTBEAM, (rstate.getBlock()==this) && (rstate.get(EASTWEST) != ew)) return state.setValue(RIGHTBEAM, (rstate.getBlock()==this) && (rstate.getValue(EASTWEST) != ew))
.with(LEFTBEAM , (lstate.getBlock()==this) && (lstate.get(EASTWEST) != ew)) .setValue(LEFTBEAM , (lstate.getBlock()==this) && (lstate.getValue(EASTWEST) != ew))
.with(DOWNCONNECT , down_connector); .setValue(DOWNCONNECT , down_connector);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState updatePostPlacement(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos) public BlockState updateShape(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos)
{ return temp_block_update_until_better(state, world, pos); } { return temp_block_update_until_better(state, world, pos); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
ItemStack held_stack = player.getHeldItem(hand); ItemStack held_stack = player.getItemInHand(hand);
if((held_stack.isEmpty()) || (held_stack.getItem() != this.asItem())) return ActionResultType.PASS; if((held_stack.isEmpty()) || (held_stack.getItem() != this.asItem())) return ActionResultType.PASS;
if(!(hit.getFace().getAxis().isVertical())) return ActionResultType.PASS; if(!(hit.getDirection().getAxis().isVertical())) return ActionResultType.PASS;
final Direction placement_direction = player.getHorizontalFacing(); final Direction placement_direction = player.getDirection();
final BlockPos adjacent_pos = pos.offset(placement_direction); final BlockPos adjacent_pos = pos.relative(placement_direction);
final BlockState adjacent = world.getBlockState(adjacent_pos); final BlockState adjacent = world.getBlockState(adjacent_pos);
final BlockItemUseContext ctx = new DirectionalPlaceContext(world, adjacent_pos, placement_direction, player.getHeldItem(hand), placement_direction.getOpposite()); final BlockItemUseContext ctx = new DirectionalPlaceContext(world, adjacent_pos, placement_direction, player.getItemInHand(hand), placement_direction.getOpposite());
if(!adjacent.isReplaceable(ctx)) return ActionResultType.func_233537_a_(world.isRemote()); if(!adjacent.canBeReplaced(ctx)) return ActionResultType.sidedSuccess(world.isClientSide());
final BlockState new_state = getStateForPlacement(ctx); final BlockState new_state = getStateForPlacement(ctx);
if(new_state == null) return ActionResultType.FAIL; if(new_state == null) return ActionResultType.FAIL;
if(!world.setBlockState(adjacent_pos, new_state, 1|2)) return ActionResultType.FAIL; if(!world.setBlock(adjacent_pos, new_state, 1|2)) return ActionResultType.FAIL;
world.playSound(player, pos, SoundEvents.BLOCK_METAL_PLACE, SoundCategory.BLOCKS, 1f, 1f); world.playSound(player, pos, SoundEvents.METAL_PLACE, SoundCategory.BLOCKS, 1f, 1f);
if(!player.isCreative()) { if(!player.isCreative()) {
held_stack.shrink(1); held_stack.shrink(1);
Inventories.setItemInPlayerHand(player, hand, held_stack); Inventories.setItemInPlayerHand(player, hand, held_stack);
} }
return ActionResultType.func_233537_a_(world.isRemote()); return ActionResultType.sidedSuccess(world.isClientSide());
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState rotate(BlockState state, Rotation rot) public BlockState rotate(BlockState state, Rotation rot)
{ return (rot==Rotation.CLOCKWISE_180) ? state : state.with(EASTWEST, !state.get(EASTWEST)); } { return (rot==Rotation.CLOCKWISE_180) ? state : state.setValue(EASTWEST, !state.getValue(EASTWEST)); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")

View file

@ -13,6 +13,7 @@ import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.world.IWorldReader; import net.minecraft.world.IWorldReader;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.material.PushReaction; import net.minecraft.block.material.PushReaction;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
@ -86,18 +87,18 @@ public class EdLabeledCrate
public static class LabeledCrateBlock extends StandardBlocks.Horizontal implements IDecorBlock public static class LabeledCrateBlock extends StandardBlocks.Horizontal implements IDecorBlock
{ {
public LabeledCrateBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB) public LabeledCrateBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState blockState, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState blockState, World world, BlockPos pos)
{ return Container.calcRedstone(world.getTileEntity(pos)); } { return Container.getRedstoneSignalFromBlockEntity(world.getBlockEntity(pos)); }
@Override @Override
public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side) public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
@ -113,10 +114,10 @@ public class EdLabeledCrate
{ return new LabeledCrateTileEntity(); } { return new LabeledCrateTileEntity(); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
if((world.isRemote) || (!stack.hasTag())) return; if((world.isClientSide) || (!stack.hasTag())) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof LabeledCrateTileEntity)) return; if(!(te instanceof LabeledCrateTileEntity)) return;
final CompoundNBT nbt = stack.getTag(); final CompoundNBT nbt = stack.getTag();
if(nbt.contains("tedata")) { if(nbt.contains("tedata")) {
@ -124,7 +125,7 @@ public class EdLabeledCrate
if(!te_nbt.isEmpty()) ((LabeledCrateTileEntity)te).readnbt(te_nbt); if(!te_nbt.isEmpty()) ((LabeledCrateTileEntity)te).readnbt(te_nbt);
} }
((LabeledCrateTileEntity)te).setCustomName(Auxiliaries.getItemLabel(stack)); ((LabeledCrateTileEntity)te).setCustomName(Auxiliaries.getItemLabel(stack));
((LabeledCrateTileEntity)te).markDirty(); ((LabeledCrateTileEntity)te).setChanged();
} }
@Override @Override
@ -135,7 +136,7 @@ public class EdLabeledCrate
public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote()) return stacks; if(world.isClientSide()) return stacks;
if(!(te instanceof LabeledCrateTileEntity)) return stacks; if(!(te instanceof LabeledCrateTileEntity)) return stacks;
if(!explosion) { if(!explosion) {
ItemStack stack = new ItemStack(this, 1); ItemStack stack = new ItemStack(this, 1);
@ -154,10 +155,10 @@ public class EdLabeledCrate
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof LabeledCrateTileEntity)) return ActionResultType.FAIL; if(!(te instanceof LabeledCrateTileEntity)) return ActionResultType.FAIL;
if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL; if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL;
NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te); NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te);
@ -165,15 +166,15 @@ public class EdLabeledCrate
} }
@Override @Override
public PushReaction getPushReaction(BlockState state) public PushReaction getPistonPushReaction(BlockState state)
{ return PushReaction.BLOCK; } { return PushReaction.BLOCK; }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(final ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(final ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ {
if(!Auxiliaries.Tooltip.extendedTipCondition() || Auxiliaries.Tooltip.helpCondition()) { if(!Auxiliaries.Tooltip.extendedTipCondition() || Auxiliaries.Tooltip.helpCondition()) {
super.addInformation(stack, world, tooltip, flag); super.appendHoverText(stack, world, tooltip, flag);
return; return;
} }
ItemStack frameStack = ItemStack.EMPTY; ItemStack frameStack = ItemStack.EMPTY;
@ -195,7 +196,7 @@ public class EdLabeledCrate
} }
} }
List<Tuple<String,Integer>> itmes = new ArrayList<>(); List<Tuple<String,Integer>> itmes = new ArrayList<>();
for(Map.Entry<Item,Integer> e:item_map.entrySet()) itmes.add(new Tuple<>(e.getKey().getTranslationKey(), e.getValue())); for(Map.Entry<Item,Integer> e:item_map.entrySet()) itmes.add(new Tuple<>(e.getKey().getDescriptionId(), e.getValue()));
itmes.sort((a,b)->b.getB()-a.getB()); itmes.sort((a,b)->b.getB()-a.getB());
boolean dotdotdot = false; boolean dotdotdot = false;
if(itmes.size() > 8) { itmes.subList(8, itmes.size()).clear(); dotdotdot = true; } if(itmes.size() > 8) { itmes.subList(8, itmes.size()).clear(); dotdotdot = true; }
@ -204,8 +205,8 @@ public class EdLabeledCrate
} }
} }
int num_free_slots = LabeledCrateTileEntity.ITEMFRAME_SLOTNO - num_used_slots; int num_free_slots = LabeledCrateTileEntity.ITEMFRAME_SLOTNO - num_used_slots;
String[] lines = Auxiliaries.localize(getTranslationKey()+".tip", new Object[] { String[] lines = Auxiliaries.localize(getDescriptionId()+".tip", new Object[] {
(frameStack.isEmpty() ? (new StringTextComponent("-/-")) : (new TranslationTextComponent(frameStack.getTranslationKey()))), (frameStack.isEmpty() ? (new StringTextComponent("-/-")) : (new TranslationTextComponent(frameStack.getDescriptionId()))),
num_used_slots, num_used_slots,
num_free_slots, num_free_slots,
total_items, total_items,
@ -271,7 +272,7 @@ public class EdLabeledCrate
} }
public ItemStack getItemFrameStack() public ItemStack getItemFrameStack()
{ return main_inventory_.getStackInSlot(ITEMFRAME_SLOTNO); } { return main_inventory_.getItem(ITEMFRAME_SLOTNO); }
protected static boolean inacceptable(ItemStack stack) protected static boolean inacceptable(ItemStack stack)
{ return (stack.hasTag() && (!stack.getTag().isEmpty()) && (unstorable_containers.contains(stack.getItem()))); } { return (stack.hasTag() && (!stack.getTag().isEmpty()) && (unstorable_containers.contains(stack.getItem()))); }
@ -294,17 +295,17 @@ public class EdLabeledCrate
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt); return nbt; } { super.save(nbt); writenbt(nbt); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
item_handler_.invalidate(); item_handler_.invalidate();
} }
@ -315,18 +316,18 @@ public class EdLabeledCrate
@Override @Override
@Nullable @Nullable
public SUpdateTileEntityPacket getUpdatePacket() public SUpdateTileEntityPacket getUpdatePacket()
{ return new SUpdateTileEntityPacket(pos, 1, getUpdateTag()); } { return new SUpdateTileEntityPacket(worldPosition, 1, getUpdateTag()); }
@Override @Override
public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) // on client public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) // on client
{ readnbt(pkt.getNbtCompound()); super.onDataPacket(net, pkt); } { readnbt(pkt.getTag()); super.onDataPacket(net, pkt); }
@Override @Override
public void handleUpdateTag(BlockState state, CompoundNBT tag) // on client public void handleUpdateTag(BlockState state, CompoundNBT tag) // on client
{ read(state, tag); } { load(state, tag); }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public double getMaxRenderDistanceSquared() public double getViewDistance()
{ return 1600; } { return 1600; }
// INameable --------------------------------------------------------------------------- // INameable ---------------------------------------------------------------------------
@ -336,7 +337,7 @@ public class EdLabeledCrate
{ {
if(custom_name_ != null) return custom_name_; if(custom_name_ != null) return custom_name_;
final Block block = getBlockState().getBlock(); final Block block = getBlockState().getBlock();
if(block!=null) return new TranslationTextComponent(block.getTranslationKey()); if(block!=null) return new TranslationTextComponent(block.getDescriptionId());
return new StringTextComponent("Labeled Crate"); return new StringTextComponent("Labeled Crate");
} }
@ -360,7 +361,7 @@ public class EdLabeledCrate
@Override @Override
public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player ) public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player )
{ return new LabeledCrateContainer(id, inventory, main_inventory_, IWorldPosCallable.of(world, pos), fields); } { return new LabeledCrateContainer(id, inventory, main_inventory_, IWorldPosCallable.create(level, worldPosition), fields); }
// Fields ----------------------------------------------------------------------------------------------- // Fields -----------------------------------------------------------------------------------------------
@ -401,11 +402,11 @@ public class EdLabeledCrate
{ super(inventory, index, x, y); } { super(inventory, index, x, y); }
@Override @Override
public int getSlotStackLimit() public int getMaxStackSize()
{ return 64; } { return 64; }
@Override @Override
public boolean isItemValid(ItemStack stack) public boolean mayPlace(ItemStack stack)
{ return !LabeledCrateTileEntity.inacceptable(stack); } { return !LabeledCrateTileEntity.inacceptable(stack); }
} }
@ -427,11 +428,11 @@ public class EdLabeledCrate
public int field(int index) { return fields_.get(index); } public int field(int index) { return fields_.get(index); }
public PlayerEntity player() { return player_ ; } public PlayerEntity player() { return player_ ; }
public IInventory inventory() { return inventory_ ; } public IInventory inventory() { return inventory_ ; }
public World world() { return player_.world; } public World world() { return player_.level; }
//------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------
public LabeledCrateContainer(int cid, PlayerInventory player_inventory) public LabeledCrateContainer(int cid, PlayerInventory player_inventory)
{ this(cid, player_inventory, new Inventory(LabeledCrateTileEntity.NUM_OF_SLOTS), IWorldPosCallable.DUMMY, new IntArray(LabeledCrateTileEntity.NUM_OF_FIELDS)); } { this(cid, player_inventory, new Inventory(LabeledCrateTileEntity.NUM_OF_SLOTS), IWorldPosCallable.NULL, new IntArray(LabeledCrateTileEntity.NUM_OF_FIELDS)); }
private LabeledCrateContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields) private LabeledCrateContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields)
{ {
@ -439,7 +440,7 @@ public class EdLabeledCrate
player_ = player_inventory.player; player_ = player_inventory.player;
inventory_ = block_inventory; inventory_ = block_inventory;
wpc_ = wpc; wpc_ = wpc;
wpc_.consume((w,p)->inventory_.openInventory(player_)); wpc_.execute((w,p)->inventory_.startOpen(player_));
fields_ = fields; fields_ = fields;
block_storage_range_ = new InventoryRange(inventory_, 0, LabeledCrateTileEntity.ITEMFRAME_SLOTNO); block_storage_range_ = new InventoryRange(inventory_, 0, LabeledCrateTileEntity.ITEMFRAME_SLOTNO);
player_inventory_range_ = new InventoryRange(player_inventory, 0, 36); player_inventory_range_ = new InventoryRange(player_inventory, 0, 36);
@ -453,7 +454,7 @@ public class EdLabeledCrate
} }
} }
// picture frame slot (54) // picture frame slot (54)
addSlot(new Slot(frame_slot_range_, 0, 191, 100) { @Override public int getSlotStackLimit(){return 1;} }); addSlot(new Slot(frame_slot_range_, 0, 191, 100) { @Override public int getMaxStackSize(){return 1;} });
// player slots // player slots
for(int x=0; x<9; ++x) { for(int x=0; x<9; ++x) {
addSlot(new Slot(player_inventory, x, 28+x*18, 183)); // player slots: 0..8 addSlot(new Slot(player_inventory, x, 28+x*18, 183)); // player slots: 0..8
@ -466,41 +467,41 @@ public class EdLabeledCrate
} }
@Override @Override
public boolean canInteractWith(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return inventory_.isUsableByPlayer(player); } { return inventory_.stillValid(player); }
@Override @Override
public boolean canMergeSlot(ItemStack stack, Slot slot) public boolean canTakeItemForPickAll(ItemStack stack, Slot slot)
{ return (slot.getSlotStackLimit() > 1); } { return (slot.getMaxStackSize() > 1); }
@Override @Override
public void onContainerClosed(PlayerEntity player) public void removed(PlayerEntity player)
{ {
super.onContainerClosed(player); super.removed(player);
inventory_.closeInventory(player); inventory_.stopOpen(player);
} }
@Override @Override
public ItemStack transferStackInSlot(PlayerEntity player, int index) public ItemStack quickMoveStack(PlayerEntity player, int index)
{ {
Slot slot = getSlot(index); Slot slot = getSlot(index);
if((slot==null) || (!slot.getHasStack())) return ItemStack.EMPTY; if((slot==null) || (!slot.hasItem())) return ItemStack.EMPTY;
ItemStack slot_stack = slot.getStack(); ItemStack slot_stack = slot.getItem();
ItemStack transferred = slot_stack.copy(); ItemStack transferred = slot_stack.copy();
if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) { if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) {
// Crate slots // Crate slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) {
// Player slot // Player slot
if(!mergeItemStack(slot_stack, 0, PLAYER_INV_START_SLOTNO-1, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, 0, PLAYER_INV_START_SLOTNO-1, false)) return ItemStack.EMPTY;
} else { } else {
// Invalid slot // Invalid slot
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
if(slot_stack.isEmpty()) { if(slot_stack.isEmpty()) {
slot.putStack(ItemStack.EMPTY); slot.set(ItemStack.EMPTY);
} else { } else {
slot.onSlotChanged(); slot.setChanged();
} }
if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY; if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY;
slot.onTake(player, slot_stack); slot.onTake(player, slot_stack);
@ -513,7 +514,7 @@ public class EdLabeledCrate
public void onGuiAction(String message, CompoundNBT nbt) public void onGuiAction(String message, CompoundNBT nbt)
{ {
nbt.putString("action", message); nbt.putString("action", message);
Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt);
} }
@Override @Override
@ -528,9 +529,9 @@ public class EdLabeledCrate
final int slotId = nbt.contains("slot") ? nbt.getInt("slot") : -1; final int slotId = nbt.contains("slot") ? nbt.getInt("slot") : -1;
switch(nbt.getString("action")) { switch(nbt.getString("action")) {
case QUICK_MOVE_ALL: { case QUICK_MOVE_ALL: {
if((slotId >= STORAGE_SLOT_BEGIN) && (slotId < STORAGE_SLOT_END) && (getSlot(slotId).getHasStack())) { if((slotId >= STORAGE_SLOT_BEGIN) && (slotId < STORAGE_SLOT_END) && (getSlot(slotId).hasItem())) {
changed = block_storage_range_.move(getSlot(slotId).getSlotIndex(), player_inventory_range_, true, false, true, true); changed = block_storage_range_.move(getSlot(slotId).getSlotIndex(), player_inventory_range_, true, false, true, true);
} else if((slotId >= PLAYER_SLOT_BEGIN) && (slotId < PLAYER_SLOT_END) && (getSlot(slotId).getHasStack())) { } else if((slotId >= PLAYER_SLOT_BEGIN) && (slotId < PLAYER_SLOT_END) && (getSlot(slotId).hasItem())) {
changed = player_inventory_range_.move(getSlot(slotId).getSlotIndex(), block_storage_range_, true, false, false, true); changed = player_inventory_range_.move(getSlot(slotId).getSlotIndex(), block_storage_range_, true, false, false, true);
} }
} break; } break;
@ -540,9 +541,9 @@ public class EdLabeledCrate
} break; } break;
} }
if(changed) { if(changed) {
inventory_.markDirty(); inventory_.setChanged();
player.inventory.markDirty(); player.inventory.setChanged();
detectAndSendChanges(); broadcastChanges();
} }
} }
} }
@ -560,10 +561,10 @@ public class EdLabeledCrate
{ {
super(container, player_inventory, title); super(container, player_inventory, title);
player_ = player_inventory.player; player_ = player_inventory.player;
xSize = 213; imageWidth = 213;
ySize = 206; imageHeight = 206;
titleX = 23; titleLabelX = 23;
titleY = -10; titleLabelY = -10;
} }
@Override @Override
@ -575,23 +576,23 @@ public class EdLabeledCrate
{ {
renderBackground/*renderBackground*/(mx); renderBackground/*renderBackground*/(mx);
super.render(mx, mouseX, mouseY, partialTicks); super.render(mx, mouseX, mouseY, partialTicks);
renderHoveredTooltip(mx, mouseX, mouseY); renderTooltip(mx, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerForegroundLayer(MatrixStack mx, int x, int y) protected void renderLabels(MatrixStack mx, int x, int y)
{ {
font.func_243248_b(mx, title, (float)titleX+1, (float)titleY+1, 0x303030); font.draw(mx, title, (float)titleLabelX+1, (float)titleLabelY+1, 0x303030);
font.func_243248_b(mx, title, (float)titleX, (float)titleY, 0x707070); font.draw(mx, title, (float)titleLabelX, (float)titleLabelY, 0x707070);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void drawGuiContainerBackgroundLayer(MatrixStack mx, float partialTicks, int mouseX, int mouseY) protected void renderBg(MatrixStack mx, float partialTicks, int mouseX, int mouseY)
{ {
GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager._color4f(1.0F, 1.0F, 1.0F, 1.0F);
getMinecraft().getTextureManager().bindTexture(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/labeled_crate_gui.png")); getMinecraft().getTextureManager().bind(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/labeled_crate_gui.png"));
final int x0=guiLeft, y0=this.guiTop, w=xSize, h=ySize; final int x0=leftPos, y0=this.topPos, w=imageWidth, h=imageHeight;
blit(mx, x0, y0, 0, 0, w, h); blit(mx, x0, y0, 0, 0, w, h);
} }
@ -601,19 +602,19 @@ public class EdLabeledCrate
{ action(message, new CompoundNBT()); } { action(message, new CompoundNBT()); }
protected void action(String message, CompoundNBT nbt) protected void action(String message, CompoundNBT nbt)
{ getContainer().onGuiAction(message, nbt); } { getMenu().onGuiAction(message, nbt); }
@Override @Override
protected void handleMouseClick(Slot slot, int slotId, int button, ClickType type) protected void slotClicked(Slot slot, int slotId, int button, ClickType type)
{ {
if(!with_gui_mouse_handling) { if(!with_gui_mouse_handling) {
super.handleMouseClick(slot, slotId, button, type); super.slotClicked(slot, slotId, button, type);
} else if((type == ClickType.QUICK_MOVE) && (slot!=null) && slot.getHasStack() && Auxiliaries.isShiftDown() && Auxiliaries.isCtrlDown()) { } else if((type == ClickType.QUICK_MOVE) && (slot!=null) && slot.hasItem() && Auxiliaries.isShiftDown() && Auxiliaries.isCtrlDown()) {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt("slot", slotId); nbt.putInt("slot", slotId);
action(LabeledCrateContainer.QUICK_MOVE_ALL, nbt); action(LabeledCrateContainer.QUICK_MOVE_ALL, nbt);
} else { } else {
super.handleMouseClick(slot, slotId, button, type); super.slotClicked(slot, slotId, button, type);
} }
} }
@ -622,14 +623,14 @@ public class EdLabeledCrate
{ {
if(!with_gui_mouse_handling) return super.mouseScrolled(mouseX, mouseY, wheel_inc); if(!with_gui_mouse_handling) return super.mouseScrolled(mouseX, mouseY, wheel_inc);
final Slot slot = getSlotUnderMouse(); final Slot slot = getSlotUnderMouse();
if((slot==null) || (!slot.getHasStack())) return true; if((slot==null) || (!slot.hasItem())) return true;
final int count = slot.getStack().getCount(); final int count = slot.getItem().getCount();
int limit = (Auxiliaries.isShiftDown() ? 2 : 1) * (Auxiliaries.isCtrlDown() ? 4 : 1); int limit = (Auxiliaries.isShiftDown() ? 2 : 1) * (Auxiliaries.isCtrlDown() ? 4 : 1);
if(wheel_inc > 0.1) { if(wheel_inc > 0.1) {
if(count > 0) { if(count > 0) {
if((count < slot.getStack().getMaxStackSize()) && (count < slot.getSlotStackLimit())) { if((count < slot.getItem().getMaxStackSize()) && (count < slot.getMaxStackSize())) {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt("slot", slot.slotNumber); nbt.putInt("slot", slot.index);
if(limit > 1) nbt.putInt("limit", limit); if(limit > 1) nbt.putInt("limit", limit);
action(LabeledCrateContainer.INCREASE_STACK, nbt); action(LabeledCrateContainer.INCREASE_STACK, nbt);
} }
@ -637,7 +638,7 @@ public class EdLabeledCrate
} else if(wheel_inc < -0.1) { } else if(wheel_inc < -0.1) {
if(count > 0) { if(count > 0) {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt("slot", slot.slotNumber); nbt.putInt("slot", slot.index);
if(limit > 1) nbt.putInt("limit", limit); if(limit > 1) nbt.putInt("limit", limit);
action(LabeledCrateContainer.DECREASE_STACK, nbt); action(LabeledCrateContainer.DECREASE_STACK, nbt);
} }

View file

@ -53,7 +53,7 @@ public class EdLadderBlock extends LadderBlock implements IDecorBlock
ModConfig.log("Config ladder: without-speed-boost:" + without_speed_boost_); ModConfig.log("Config ladder: without-speed-boost:" + without_speed_boost_);
} }
public EdLadderBlock(long config, Block.Properties builder) public EdLadderBlock(long config, AbstractBlock.Properties builder)
{ super(builder); } { super(builder); }
@Override @Override
@ -62,12 +62,12 @@ public class EdLadderBlock extends LadderBlock implements IDecorBlock
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); } { Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); }
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos) public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos)
{ {
switch ((Direction)state.get(FACING)) { switch ((Direction)state.getValue(FACING)) {
case NORTH: return EDLADDER_NORTH_AABB; case NORTH: return EDLADDER_NORTH_AABB;
case SOUTH: return EDLADDER_SOUTH_AABB; case SOUTH: return EDLADDER_SOUTH_AABB;
case WEST: return EDLADDER_WEST_AABB; case WEST: return EDLADDER_WEST_AABB;
@ -76,7 +76,7 @@ public class EdLadderBlock extends LadderBlock implements IDecorBlock
} }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@ -85,7 +85,7 @@ public class EdLadderBlock extends LadderBlock implements IDecorBlock
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public PushReaction getPushReaction(BlockState state) public PushReaction getPistonPushReaction(BlockState state)
{ return PushReaction.NORMAL; } { return PushReaction.NORMAL; }
@Override @Override
@ -95,23 +95,23 @@ public class EdLadderBlock extends LadderBlock implements IDecorBlock
// Player update event, forwarded from the main mod instance. // Player update event, forwarded from the main mod instance.
public static void onPlayerUpdateEvent(final PlayerEntity player) public static void onPlayerUpdateEvent(final PlayerEntity player)
{ {
if((without_speed_boost_) || (player.isOnGround()) || (!player.isOnLadder()) || (player.isSteppingCarefully()) || (player.isSpectator())) return; if((without_speed_boost_) || (player.isOnGround()) || (!player.onClimbable()) || (player.isSteppingCarefully()) || (player.isSpectator())) return;
double lvy = player.getLookVec().y; double lvy = player.getLookAngle().y;
if(Math.abs(lvy) < 0.92) return; if(Math.abs(lvy) < 0.92) return;
final BlockPos pos = player.getPosition(); final BlockPos pos = player.blockPosition();
final BlockState state = player.world.getBlockState(pos); final BlockState state = player.level.getBlockState(pos);
if(!(state.getBlock() instanceof EdLadderBlock)) return; if(!(state.getBlock() instanceof EdLadderBlock)) return;
player.fallDistance = 0; player.fallDistance = 0;
if((player.getMotion().getY() < 0) == (player.getLookVec().y < 0)) { if((player.getDeltaMovement().y() < 0) == (player.getLookAngle().y < 0)) {
player.setMotionMultiplier(state, new Vector3d(0.2, (lvy>0)?(3):(6), 0.2)); player.makeStuckInBlock(state, new Vector3d(0.2, (lvy>0)?(3):(6), 0.2));
if(Math.abs(player.getMotion().getY()) > 0.1) { if(Math.abs(player.getDeltaMovement().y()) > 0.1) {
Vector3d vdiff = Vector3d.copyCenteredHorizontally(pos).subtract(player.getPositionVec()).scale(1); Vector3d vdiff = Vector3d.atBottomCenterOf(pos).subtract(player.position()).scale(1);
vdiff.add(Vector3d.copyCenteredHorizontally(state.get(FACING).getDirectionVec()).scale(0.5)); vdiff.add(Vector3d.atBottomCenterOf(state.getValue(FACING).getNormal()).scale(0.5));
vdiff = new Vector3d(vdiff.x, player.getMotion().y, vdiff.z); vdiff = new Vector3d(vdiff.x, player.getDeltaMovement().y, vdiff.z);
player.setMotion(vdiff); player.setDeltaMovement(vdiff);
} }
} else if(player.getLookVec().y > 0) { } else if(player.getLookAngle().y > 0) {
player.setMotionMultiplier(state, new Vector3d(1, 0.05, 1)); player.makeStuckInBlock(state, new Vector3d(1, 0.05, 1));
} }
} }

View file

@ -11,6 +11,7 @@ package wile.engineersdecor.blocks;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.IWorldReader; import net.minecraft.world.IWorldReader;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.state.BooleanProperty; import net.minecraft.state.BooleanProperty;
@ -72,26 +73,26 @@ public class EdMilker
public static final BooleanProperty FILLED = BooleanProperty.create("filled"); public static final BooleanProperty FILLED = BooleanProperty.create("filled");
public static final BooleanProperty ACTIVE = BooleanProperty.create("active"); public static final BooleanProperty ACTIVE = BooleanProperty.create("active");
public MilkerBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABBs) public MilkerBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABBs)
{ super(config, builder, unrotatedAABBs); } { super(config, builder, unrotatedAABBs); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(ACTIVE); builder.add(FILLED); } { super.createBlockStateDefinition(builder); builder.add(ACTIVE); builder.add(FILLED); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(FILLED, false).with(ACTIVE, false); } { return super.getStateForPlacement(context).setValue(FILLED, false).setValue(ACTIVE, false); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState state, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState state, World world, BlockPos pos)
{ {
MilkerTileEntity te = getTe(world, pos); MilkerTileEntity te = getTe(world, pos);
return (te==null) ? 0 : MathHelper.clamp((16 * te.fluid_level())/MilkerTileEntity.TANK_CAPACITY, 0, 15); return (te==null) ? 0 : MathHelper.clamp((16 * te.fluid_level())/MilkerTileEntity.TANK_CAPACITY, 0, 15);
@ -112,12 +113,12 @@ public class EdMilker
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
MilkerTileEntity te = getTe(world, pos); MilkerTileEntity te = getTe(world, pos);
if(te==null) return ActionResultType.FAIL; if(te==null) return ActionResultType.FAIL;
final ItemStack in_stack = player.getHeldItem(hand); final ItemStack in_stack = player.getItemInHand(hand);
final ItemStack out_stack = MilkerTileEntity.milk_filled_container_item(in_stack); final ItemStack out_stack = MilkerTileEntity.milk_filled_container_item(in_stack);
if(in_stack.isEmpty()) { if(in_stack.isEmpty()) {
te.state_message(player); te.state_message(player);
@ -135,15 +136,15 @@ public class EdMilker
in_stack.shrink(1); in_stack.shrink(1);
drained = true; drained = true;
if(remainder.getCount() > 0) { if(remainder.getCount() > 0) {
final ItemEntity ei = new ItemEntity(world, player.getPositionVec().getX(), player.getPositionVec().getY()+0.5, player.getPositionVec().getZ(), remainder); final ItemEntity ei = new ItemEntity(world, player.position().x(), player.position().y()+0.5, player.position().z(), remainder);
ei.setPickupDelay(40); ei.setPickUpDelay(40);
ei.setMotion(0,0,0); ei.setDeltaMovement(0,0,0);
world.addEntity(ei); world.addFreshEntity(ei);
} }
} }
} }
if(drained) { if(drained) {
world.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL, SoundCategory.BLOCKS, 0.8f, 1f); world.playSound(null, pos, SoundEvents.BUCKET_FILL, SoundCategory.BLOCKS, 0.8f, 1f);
} }
} }
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
@ -151,7 +152,7 @@ public class EdMilker
@Nullable @Nullable
private MilkerTileEntity getTe(World world, BlockPos pos) private MilkerTileEntity getTe(World world, BlockPos pos)
{ final TileEntity te=world.getTileEntity(pos); return (!(te instanceof MilkerTileEntity)) ? (null) : ((MilkerTileEntity)te); } { final TileEntity te=world.getBlockEntity(pos); return (!(te instanceof MilkerTileEntity)) ? (null) : ((MilkerTileEntity)te); }
} }
//-------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------
@ -175,7 +176,7 @@ public class EdMilker
private enum MilkingState { IDLE, PICKED, COMING, POSITIONING, MILKING, LEAVING, WAITING } private enum MilkingState { IDLE, PICKED, COMING, POSITIONING, MILKING, LEAVING, WAITING }
private static FluidStack milk_fluid_ = NO_MILK_FLUID; private static FluidStack milk_fluid_ = NO_MILK_FLUID;
private static HashMap<ItemStack, ItemStack> milk_containers_ = new HashMap<>(); private static final HashMap<ItemStack, ItemStack> milk_containers_ = new HashMap<>();
private static int energy_consumption_ = DEFAULT_ENERGY_CONSUMPTION; private static int energy_consumption_ = DEFAULT_ENERGY_CONSUMPTION;
private static long min_milking_delay_per_cow_ticks_ = DEFAULT_MILKING_DELAY_PER_COW; private static long min_milking_delay_per_cow_ticks_ = DEFAULT_MILKING_DELAY_PER_COW;
private int tick_timer_; private int tick_timer_;
@ -240,7 +241,7 @@ public class EdMilker
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
writenbt(nbt, false); reset(); writenbt(nbt, false); reset();
if(cowuid == null) return nbt; if(cowuid == null) return nbt;
world.getEntitiesWithinAABB(CowEntity.class, new AxisAlignedBB(pos).grow(16, 16, 16), e->e.getUniqueID().equals(cowuid)).forEach(e->e.setNoAI(false)); level.getEntitiesOfClass(CowEntity.class, new AxisAlignedBB(worldPosition).inflate(16, 16, 16), e->e.getUUID().equals(cowuid)).forEach(e->e.setNoAi(false));
return nbt; return nbt;
} }
@ -274,17 +275,17 @@ public class EdMilker
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt, false); } { super.load(state, nbt); readnbt(nbt, false); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt, false); return nbt; } { super.save(nbt); writenbt(nbt, false); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
energy_handler_.invalidate(); energy_handler_.invalidate();
fluid_handler_.invalidate(); fluid_handler_.invalidate();
} }
@ -351,8 +352,8 @@ public class EdMilker
private boolean fill_adjacent_inventory_item_containers(Direction block_facing) private boolean fill_adjacent_inventory_item_containers(Direction block_facing)
{ {
// Check inventory existence, back to down is preferred, otherwise sort back into same inventory. // Check inventory existence, back to down is preferred, otherwise sort back into same inventory.
IItemHandler src = Inventories.itemhandler(world, pos.offset(block_facing), block_facing.getOpposite()); IItemHandler src = Inventories.itemhandler(level, worldPosition.relative(block_facing), block_facing.getOpposite());
IItemHandler dst = Inventories.itemhandler(world, pos.down(), Direction.UP); IItemHandler dst = Inventories.itemhandler(level, worldPosition.below(), Direction.UP);
if(src==null) { src = dst; } else if(dst==null) { dst = src; } if(src==null) { src = dst; } else if(dst==null) { dst = src; }
if((src==null) || (dst==null)) return false; if((src==null) || (dst==null)) return false;
boolean dirty = false; boolean dirty = false;
@ -377,7 +378,7 @@ public class EdMilker
if((fluid_level()<=0) || (!has_milk_fluid())) return false; if((fluid_level()<=0) || (!has_milk_fluid())) return false;
final FluidStack fs = new FluidStack(milk_fluid_, Math.max(fluid_level(), BUCKET_SIZE)); final FluidStack fs = new FluidStack(milk_fluid_, Math.max(fluid_level(), BUCKET_SIZE));
for(Direction dir:Direction.values()) { for(Direction dir:Direction.values()) {
int amount = Fluidics.fill(getWorld(), getPos().offset(dir), dir.getOpposite(), fs); int amount = Fluidics.fill(getLevel(), getBlockPos().relative(dir), dir.getOpposite(), fs);
if(amount > 0) { if(amount > 0) {
tank_.drain(amount); tank_.drain(amount);
return true; return true;
@ -390,10 +391,10 @@ public class EdMilker
{ {
log("release cow"); log("release cow");
if(cow != null) { if(cow != null) {
cow.setNoAI(false); cow.setNoAi(false);
SingleMoveGoal.abortFor(cow); SingleMoveGoal.abortFor(cow);
tracked_cows_.remove(cow.getEntityId()); tracked_cows_.remove(cow.getId());
for(int id:tracked_cows_.keySet().stream().filter(i->cow.getEntityWorld().getEntityByID(i)==null).collect(Collectors.toList())) { for(int id:tracked_cows_.keySet().stream().filter(i->cow.getCommandSenderWorld().getEntity(i)==null).collect(Collectors.toList())) {
tracked_cows_.remove(id); tracked_cows_.remove(id);
} }
} }
@ -405,25 +406,25 @@ public class EdMilker
private boolean milking_process() private boolean milking_process()
{ {
if((tracked_cow_ == null) && (fluid_level() >= MAX_MILKING_TANK_LEVEL)) return false; // nothing to do if((tracked_cow_ == null) && (fluid_level() >= MAX_MILKING_TANK_LEVEL)) return false; // nothing to do
final Direction facing = world.getBlockState(getPos()).get(MilkerBlock.HORIZONTAL_FACING).getOpposite(); final Direction facing = level.getBlockState(getBlockPos()).getValue(MilkerBlock.HORIZONTAL_FACING).getOpposite();
final Vector3d target_pos = Vector3d.copy(getPos().offset(facing)).add(0.5,0,0.5); final Vector3d target_pos = Vector3d.atLowerCornerOf(getBlockPos().relative(facing)).add(0.5,0,0.5);
CowEntity cow = null; CowEntity cow = null;
{ {
AxisAlignedBB aabb = new AxisAlignedBB(pos.offset(facing, 3)).grow(4, 2, 4); AxisAlignedBB aabb = new AxisAlignedBB(worldPosition.relative(facing, 3)).inflate(4, 2, 4);
final long t = world.getGameTime(); final long t = level.getGameTime();
final List<CowEntity> cows = world.getEntitiesWithinAABB(CowEntity.class, aabb, final List<CowEntity> cows = level.getEntitiesOfClass(CowEntity.class, aabb,
e-> { e-> {
if(e.getUniqueID().equals(tracked_cow_)) return true; if(e.getUUID().equals(tracked_cow_)) return true;
if((tracked_cow_!=null) || e.isChild() || e.isInLove() || e.isBeingRidden()) return false; if((tracked_cow_!=null) || e.isBaby() || e.isInLove() || e.isVehicle()) return false;
if(!e.getNavigator().noPath()) return false; if(!e.getNavigation().isDone()) return false;
if(Math.abs(tracked_cows_.getOrDefault(e.getEntityId(), 0L)-t) < min_milking_delay_per_cow_ticks_) return false; if(Math.abs(tracked_cows_.getOrDefault(e.getId(), 0L)-t) < min_milking_delay_per_cow_ticks_) return false;
return true; return true;
} }
); );
if(cows.size() == 1) { if(cows.size() == 1) {
cow = cows.get(0); // tracked or only one cow = cows.get(0); // tracked or only one
} else if(cows.size() > 1) { } else if(cows.size() > 1) {
cow = cows.get(world.rand.nextInt(cows.size()-1)); // pick one cow = cows.get(level.random.nextInt(cows.size()-1)); // pick one
} }
} }
if((state_ != MilkingState.IDLE) && ((state_timeout_ -= PROCESSING_TICK_INTERVAL) <= 0)) { release_cow(cow); log("Cow motion timeout"); cow = null; } if((state_ != MilkingState.IDLE) && ((state_timeout_ -= PROCESSING_TICK_INTERVAL) <= 0)) { release_cow(cow); log("Cow motion timeout"); cow = null; }
@ -435,35 +436,35 @@ public class EdMilker
if(state_timer_ > 0) return false; if(state_timer_ > 0) return false;
switch(state_) { // Let's do this the old school FSA sequencing way ... switch(state_) { // Let's do this the old school FSA sequencing way ...
case IDLE: { case IDLE: {
final List<LivingEntity> blocking_entities = world.getEntitiesWithinAABB(LivingEntity.class, new AxisAlignedBB(pos.offset(facing)).grow(0.5, 0.5, 0.5)); final List<LivingEntity> blocking_entities = level.getEntitiesOfClass(LivingEntity.class, new AxisAlignedBB(worldPosition.relative(facing)).inflate(0.5, 0.5, 0.5));
if(blocking_entities.size() > 0) { if(blocking_entities.size() > 0) {
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
log("Idle: Position blocked"); log("Idle: Position blocked");
if(blocking_entities.get(0) instanceof CowEntity) { if(blocking_entities.get(0) instanceof CowEntity) {
CowEntity blocker = (CowEntity)blocking_entities.get(0); CowEntity blocker = (CowEntity)blocking_entities.get(0);
BlockPos p = getPos().offset(facing,2); BlockPos p = getBlockPos().relative(facing,2);
log("Idle: Shove off"); log("Idle: Shove off");
blocker.setNoAI(false); blocker.setNoAi(false);
SingleMoveGoal.startFor(blocker, p, 2, 1.0, (goal, world, pos)->(pos.distanceSq(goal.getCreature().getPosition())>100)); SingleMoveGoal.startFor(blocker, p, 2, 1.0, (goal, world, pos)->(pos.distSqr(goal.getCreature().blockPosition())>100));
} }
return false; return false;
} }
if(cow.getLeashed() || cow.isChild() || cow.isInLove() || (!cow.isOnGround()) || cow.isBeingRidden() || cow.isSprinting()) return false; if(cow.isLeashed() || cow.isBaby() || cow.isInLove() || (!cow.isOnGround()) || cow.isVehicle() || cow.isSprinting()) return false;
tracked_cows_.put(cow.getEntityId(), cow.getEntityWorld().getGameTime()); tracked_cows_.put(cow.getId(), cow.getCommandSenderWorld().getGameTime());
tracked_cow_ = cow.getUniqueID(); tracked_cow_ = cow.getUUID();
state_ = MilkingState.PICKED; state_ = MilkingState.PICKED;
state_timeout_ = 200; state_timeout_ = 200;
tracked_cow_original_position_ = cow.getPosition(); tracked_cow_original_position_ = cow.blockPosition();
log("Idle: Picked cow " + tracked_cow_); log("Idle: Picked cow " + tracked_cow_);
return false; return false;
} }
case PICKED: { case PICKED: {
SingleMoveGoal.startFor( SingleMoveGoal.startFor(
cow, target_pos, 2, 1.0, cow, target_pos, 2, 1.0,
(goal, world, pos)->(pos.distanceSq(goal.getCreature().getPosition())>100), (goal, world, pos)->(pos.distSqr(goal.getCreature().blockPosition())>100),
(goal, world, pos)->{ (goal, world, pos)->{
log("move: position reached"); log("move: position reached");
goal.getCreature().setLocationAndAngles(goal.getTargetPosition().getX(), goal.getTargetPosition().getY(), goal.getTargetPosition().getZ(), facing.getHorizontalAngle(), 0); goal.getCreature().moveTo(goal.getTargetPosition().x(), goal.getTargetPosition().y(), goal.getTargetPosition().z(), facing.toYRot(), 0);
}, },
(goal, world, pos)->{ (goal, world, pos)->{
log("move: aborted"); log("move: aborted");
@ -475,7 +476,7 @@ public class EdMilker
return false; return false;
} }
case COMING: { case COMING: {
if(target_pos.squareDistanceTo(cow.getPositionVec()) <= 1) { if(target_pos.distanceToSqr(cow.position()) <= 1) {
log("Coming: position reached"); log("Coming: position reached");
state_ = MilkingState.POSITIONING; state_ = MilkingState.POSITIONING;
state_timeout_ = 100; // 5s state_timeout_ = 100; // 5s
@ -490,9 +491,9 @@ public class EdMilker
case POSITIONING: { case POSITIONING: {
log("Positioning: start milking"); log("Positioning: start milking");
SingleMoveGoal.abortFor(cow); SingleMoveGoal.abortFor(cow);
cow.setNoAI(true); cow.setNoAi(true);
cow.setLocationAndAngles(target_pos.getX(), target_pos.getY(), target_pos.getZ(), facing.getHorizontalAngle(), 0); cow.moveTo(target_pos.x(), target_pos.y(), target_pos.z(), facing.toYRot(), 0);
world.playSound(null, pos, SoundEvents.ENTITY_COW_MILK, SoundCategory.BLOCKS, 0.5f, 1f); level.playSound(null, worldPosition, SoundEvents.COW_MILK, SoundCategory.BLOCKS, 0.5f, 1f);
state_timeout_ = 600; state_timeout_ = 600;
state_ = MilkingState.MILKING; state_ = MilkingState.MILKING;
state_timer_ = 30; state_timer_ = 30;
@ -503,19 +504,19 @@ public class EdMilker
state_timeout_ = 600; state_timeout_ = 600;
state_ = MilkingState.LEAVING; state_ = MilkingState.LEAVING;
state_timer_ = 20; state_timer_ = 20;
cow.setNoAI(false); cow.setNoAi(false);
cow.getNavigator().clearPath(); cow.getNavigation().stop();
log("Milking: done, leave"); log("Milking: done, leave");
return true; return true;
} }
case LEAVING: { case LEAVING: {
BlockPos p = (tracked_cow_original_position_ != null) ? (tracked_cow_original_position_) : getPos().offset(facing,2).offset(facing.rotateYCCW()); BlockPos p = (tracked_cow_original_position_ != null) ? (tracked_cow_original_position_) : getBlockPos().relative(facing,2).relative(facing.getCounterClockWise());
SingleMoveGoal.startFor(cow, p, 2, 1.0, (goal, world, pos)->(pos.distanceSq(goal.getCreature().getPosition())>100)); SingleMoveGoal.startFor(cow, p, 2, 1.0, (goal, world, pos)->(pos.distSqr(goal.getCreature().blockPosition())>100));
state_timeout_ = 600; state_timeout_ = 600;
state_timer_ = 500; state_timer_ = 500;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
state_ = MilkingState.WAITING; state_ = MilkingState.WAITING;
tracked_cows_.put(cow.getEntityId(), cow.getEntityWorld().getGameTime()); tracked_cows_.put(cow.getId(), cow.getCommandSenderWorld().getGameTime());
log("Leaving: process done"); log("Leaving: process done");
return true; return true;
} }
@ -539,12 +540,12 @@ public class EdMilker
@Override @Override
public void tick() public void tick()
{ {
if((world.isRemote) || ((--tick_timer_ > 0))) return; if((level.isClientSide) || ((--tick_timer_ > 0))) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
boolean dirty = false; boolean dirty = false;
final BlockState block_state = world.getBlockState(pos); final BlockState block_state = level.getBlockState(worldPosition);
if(!(block_state.getBlock() instanceof MilkerBlock)) return; if(!(block_state.getBlock() instanceof MilkerBlock)) return;
if(!world.isBlockPowered(pos) || (state_ != MilkingState.IDLE)) { if(!level.hasNeighborSignal(worldPosition) || (state_ != MilkingState.IDLE)) {
if((energy_consumption_ > 0) && (!battery_.draw(energy_consumption_))) return; if((energy_consumption_ > 0) && (!battery_.draw(energy_consumption_))) return;
// Track and milk cows // Track and milk cows
if(milking_process()) dirty = true; if(milking_process()) dirty = true;
@ -552,7 +553,7 @@ public class EdMilker
if(has_milk_fluid() && (!tank_.isEmpty())) { if(has_milk_fluid() && (!tank_.isEmpty())) {
log("Fluid transfer"); log("Fluid transfer");
for(Direction facing: FLUID_TRANSFER_DIRECTRIONS) { for(Direction facing: FLUID_TRANSFER_DIRECTRIONS) {
final IFluidHandler fh = FluidUtil.getFluidHandler(world, pos.offset(facing), facing.getOpposite()).orElse(null); final IFluidHandler fh = FluidUtil.getFluidHandler(level, worldPosition.relative(facing), facing.getOpposite()).orElse(null);
if(fh == null) continue; if(fh == null) continue;
final FluidStack fs = tank_.drain(BUCKET_SIZE, FluidAction.SIMULATE); final FluidStack fs = tank_.drain(BUCKET_SIZE, FluidAction.SIMULATE);
int nfilled = fh.fill(fs, FluidAction.EXECUTE); int nfilled = fh.fill(fs, FluidAction.EXECUTE);
@ -565,13 +566,13 @@ public class EdMilker
// Adjacent inventory update, only done just after milking to prevent waste of server cpu. // Adjacent inventory update, only done just after milking to prevent waste of server cpu.
if((!dirty) && (fluid_level() > 0)) { if((!dirty) && (fluid_level() > 0)) {
log("Try item transfer"); log("Try item transfer");
if(fill_adjacent_tank() || ((fluid_level() >= BUCKET_SIZE) && fill_adjacent_inventory_item_containers(block_state.get(MilkerBlock.HORIZONTAL_FACING)))) dirty = true; if(fill_adjacent_tank() || ((fluid_level() >= BUCKET_SIZE) && fill_adjacent_inventory_item_containers(block_state.getValue(MilkerBlock.HORIZONTAL_FACING)))) dirty = true;
} }
} }
// State update // State update
BlockState new_state = block_state.with(MilkerBlock.FILLED, fluid_level()>=FILLED_INDICATION_THRESHOLD).with(MilkerBlock.ACTIVE, state_==MilkingState.MILKING); BlockState new_state = block_state.setValue(MilkerBlock.FILLED, fluid_level()>=FILLED_INDICATION_THRESHOLD).setValue(MilkerBlock.ACTIVE, state_==MilkingState.MILKING);
if(block_state != new_state) world.setBlockState(pos, new_state,1|2|16); if(block_state != new_state) level.setBlock(worldPosition, new_state,1|2|16);
if(dirty) markDirty(); if(dirty) setChanged();
} }
} }
@ -597,9 +598,9 @@ public class EdMilker
abort_condition_ = abort_condition; abort_condition_ = abort_condition;
on_target_position_reached_ = on_position_reached; on_target_position_reached_ = on_position_reached;
on_aborted_ = on_aborted; on_aborted_ = on_aborted;
destinationBlock = new BlockPos(pos.getX(), pos.getY(), pos.getZ()); blockPos = new BlockPos(pos.x(), pos.y(), pos.z());
timeoutCounter = 0; tryTicks = 0;
runDelay = 0; nextStartTick = 0;
aborted_ = false; aborted_ = false;
was_aborted_ = false; was_aborted_ = false;
target_pos_ = pos; target_pos_ = pos;
@ -611,14 +612,14 @@ public class EdMilker
public static boolean startFor(CreatureEntity entity, Vector3d target_pos, int priority, double speed, TargetPositionInValidCheck abort_condition, @Nullable StrollEvent on_position_reached, @Nullable StrollEvent on_aborted) public static boolean startFor(CreatureEntity entity, Vector3d target_pos, int priority, double speed, TargetPositionInValidCheck abort_condition, @Nullable StrollEvent on_position_reached, @Nullable StrollEvent on_aborted)
{ {
synchronized(tracked_entities_) { synchronized(tracked_entities_) {
SingleMoveGoal goal = tracked_entities_.getOrDefault(entity.getEntityId(), null); SingleMoveGoal goal = tracked_entities_.getOrDefault(entity.getId(), null);
if(goal != null) { if(goal != null) {
if(!goal.aborted()) return false; // that is still running. if(!goal.aborted()) return false; // that is still running.
entity.goalSelector.removeGoal(goal); entity.goalSelector.removeGoal(goal);
} }
log("::start("+entity.getEntityId()+")"); log("::start("+entity.getId()+")");
goal = new SingleMoveGoal(entity, target_pos, speed, abort_condition, on_position_reached, on_aborted); goal = new SingleMoveGoal(entity, target_pos, speed, abort_condition, on_position_reached, on_aborted);
tracked_entities_.put(entity.getEntityId(), goal); tracked_entities_.put(entity.getId(), goal);
entity.goalSelector.addGoal(priority, goal); entity.goalSelector.addGoal(priority, goal);
return true; return true;
} }
@ -631,14 +632,14 @@ public class EdMilker
public static void abortFor(CreatureEntity entity) public static void abortFor(CreatureEntity entity)
{ {
log("::abort("+entity.getEntityId()+")"); log("::abort("+entity.getId()+")");
if(entity.isAlive()) { if(entity.isAlive()) {
entity.goalSelector.getRunningGoals().filter(g->(g.getGoal()) instanceof SingleMoveGoal).forEach(g->((SingleMoveGoal)g.getGoal()).abort()); entity.goalSelector.getRunningGoals().filter(g->(g.getGoal()) instanceof SingleMoveGoal).forEach(g->((SingleMoveGoal)g.getGoal()).abort());
} }
final World world = entity.getEntityWorld(); final World world = entity.getCommandSenderWorld();
if(world != null) { if(world != null) {
// @todo: check nicer way to filter a map. // @todo: check nicer way to filter a map.
List<Integer> to_remove = tracked_entities_.keySet().stream().filter(i->(world.getEntityByID(i) == null)).collect(Collectors.toList()); List<Integer> to_remove = tracked_entities_.keySet().stream().filter(i->(world.getEntity(i) == null)).collect(Collectors.toList());
for(int id:to_remove)tracked_entities_.remove(id); for(int id:to_remove)tracked_entities_.remove(id);
} }
} }
@ -647,7 +648,7 @@ public class EdMilker
{ return target_pos_; } { return target_pos_; }
public CreatureEntity getCreature() public CreatureEntity getCreature()
{ return creature; } { return mob; }
public synchronized void abort() public synchronized void abort()
{ aborted_ = true; } { aborted_ = true; }
@ -660,50 +661,50 @@ public class EdMilker
abort_condition_ = abort_condition; abort_condition_ = abort_condition;
on_target_position_reached_ = on_position_reached; on_target_position_reached_ = on_position_reached;
on_aborted_ = on_aborted; on_aborted_ = on_aborted;
destinationBlock = new BlockPos(target_pos.getX(), target_pos.getY(), target_pos.getZ()); blockPos = new BlockPos(target_pos.x(), target_pos.y(), target_pos.z());
timeoutCounter = 0; tryTicks = 0;
runDelay = 0; nextStartTick = 0;
aborted_ = false; aborted_ = false;
was_aborted_ = false; was_aborted_ = false;
target_pos_ = new Vector3d(target_pos.getX(), target_pos.getY(), target_pos.getZ()); target_pos_ = new Vector3d(target_pos.x(), target_pos.y(), target_pos.z());
// this.movementSpeed = speed; -> that is final, need to override tick and func_whatever // this.movementSpeed = speed; -> that is final, need to override tick and func_whatever
} }
@Override @Override
public void resetTask() public void stop()
{ runDelay = 0; timeoutCounter = 0; } { nextStartTick = 0; tryTicks = 0; }
@Override @Override
public double getTargetDistanceSq() public double acceptedDistance()
{ return 0.7; } { return 0.7; }
@Override @Override
public boolean shouldMove() public boolean shouldRecalculatePath()
{ return (!aborted()) && (timeoutCounter & 0x7) == 0; } { return (!aborted()) && (tryTicks & 0x7) == 0; }
@Override @Override
public boolean shouldExecute() public boolean canUse()
{ {
if(aborted_) { if(aborted_) {
if((!was_aborted_) && (on_aborted_!=null)) on_aborted_.apply(this, creature.world, target_pos_); if((!was_aborted_) && (on_aborted_!=null)) on_aborted_.apply(this, mob.level, target_pos_);
was_aborted_ = true; was_aborted_ = true;
return false; return false;
} else if(!shouldMoveTo(creature.world, destinationBlock)) { } else if(!isValidTarget(mob.level, blockPos)) {
synchronized(this) { aborted_ = true; } synchronized(this) { aborted_ = true; }
return false; return false;
} else if(--runDelay > 0) { } else if(--nextStartTick > 0) {
return false; return false;
} else { } else {
runDelay = 10; nextStartTick = 10;
return true; return true;
} }
} }
@Override @Override
public void startExecuting() public void start()
{ {
timeoutCounter = 0; tryTicks = 0;
if(!creature.getNavigator().tryMoveToXYZ(target_pos_.getX(), target_pos_.getY(), target_pos_.getZ(), this.movementSpeed)) { if(!mob.getNavigation().moveTo(target_pos_.x(), target_pos_.y(), target_pos_.z(), this.speedModifier)) {
abort(); abort();
log("startExecuting() -> abort, no path"); log("startExecuting() -> abort, no path");
} else { } else {
@ -711,24 +712,24 @@ public class EdMilker
} }
} }
public boolean shouldContinueExecuting() public boolean canContinueToUse()
{ {
if(aborted()) { if(aborted()) {
log("shouldContinueExecuting() -> already aborted"); log("shouldContinueExecuting() -> already aborted");
return false; return false;
} else if(creature.getNavigator().noPath()) { } else if(mob.getNavigation().isDone()) {
if((!creature.getNavigator().setPath(creature.getNavigator().getPathToPos(target_pos_.getX(), target_pos_.getY(), target_pos_.getZ(), 0), movementSpeed))) { if((!mob.getNavigation().moveTo(mob.getNavigation().createPath(target_pos_.x(), target_pos_.y(), target_pos_.z(), 0), speedModifier))) {
log("shouldContinueExecuting() -> abort, no path"); log("shouldContinueExecuting() -> abort, no path");
abort(); abort();
return false; return false;
} else { } else {
return true; return true;
} }
} else if(timeoutCounter > motion_timeout) { } else if(tryTicks > motion_timeout) {
log("shouldContinueExecuting() -> abort, timeout"); log("shouldContinueExecuting() -> abort, timeout");
abort(); abort();
return false; return false;
} else if(!shouldMoveTo(creature.world, destinationBlock)) { } else if(!isValidTarget(mob.level, blockPos)) {
log("shouldContinueExecuting() -> abort, !shouldMoveTo()"); log("shouldContinueExecuting() -> abort, !shouldMoveTo()");
abort(); abort();
return false; return false;
@ -739,7 +740,7 @@ public class EdMilker
} }
@Override @Override
protected boolean shouldMoveTo(IWorldReader world, BlockPos pos) protected boolean isValidTarget(IWorldReader world, BlockPos pos)
{ {
if(abort_condition_.test(this, world, pos)) { if(abort_condition_.test(this, world, pos)) {
log("shouldMoveTo() -> abort_condition"); log("shouldMoveTo() -> abort_condition");
@ -752,14 +753,14 @@ public class EdMilker
@Override @Override
public void tick() public void tick()
{ {
BlockPos testpos = new BlockPos(target_pos_.getX(), creature.getPositionVec().getY(), target_pos_.getZ()); BlockPos testpos = new BlockPos(target_pos_.x(), mob.position().y(), target_pos_.z());
if(!testpos.withinDistance(creature.getPositionVec(), getTargetDistanceSq())) { if(!testpos.closerThan(mob.position(), acceptedDistance())) {
if((++timeoutCounter > motion_timeout)) { if((++tryTicks > motion_timeout)) {
log("tick() -> abort, timeoutCounter"); log("tick() -> abort, timeoutCounter");
abort(); abort();
return; return;
} }
if(shouldMove() && (!creature.getNavigator().tryMoveToXYZ(target_pos_.getX(), target_pos_.getY(), target_pos_.getZ(), movementSpeed))) { if(shouldRecalculatePath() && (!mob.getNavigation().moveTo(target_pos_.x(), target_pos_.y(), target_pos_.z(), speedModifier))) {
log("tick() -> abort, !tryMoveToXYZ()"); log("tick() -> abort, !tryMoveToXYZ()");
abort(); abort();
} }
@ -767,7 +768,7 @@ public class EdMilker
log("tick() -> abort, in position)"); log("tick() -> abort, in position)");
in_position_ = true; in_position_ = true;
abort(); abort();
if(on_target_position_reached_ != null) on_target_position_reached_.apply(this, creature.world, target_pos_); if(on_target_position_reached_ != null) on_target_position_reached_.apply(this, mob.level, target_pos_);
} }
} }
} }

View file

@ -69,27 +69,27 @@ public class EdMineralSmelter
public static final int PHASE_MAX = 3; public static final int PHASE_MAX = 3;
public static final IntegerProperty PHASE = IntegerProperty.create("phase", 0, PHASE_MAX); public static final IntegerProperty PHASE = IntegerProperty.create("phase", 0, PHASE_MAX);
public MineralSmelterBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB) public MineralSmelterBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(PHASE); } { super.createBlockStateDefinition(builder); builder.add(PHASE); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(PHASE, 0); } { return super.getStateForPlacement(context).setValue(PHASE, 0); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState state, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState state, World world, BlockPos pos)
{ return MathHelper.clamp((state.get(PHASE)*5), 0, 15); } { return MathHelper.clamp((state.getValue(PHASE)*5), 0, 15); }
@Override @Override
public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side) public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
@ -105,7 +105,7 @@ public class EdMineralSmelter
{ return new EdMineralSmelter.MineralSmelterTileEntity(); } { return new EdMineralSmelter.MineralSmelterTileEntity(); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{} {}
@Override @Override
@ -116,7 +116,7 @@ public class EdMineralSmelter
public List<ItemStack> dropList(BlockState state, World world, TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof MineralSmelterTileEntity)) return stacks; if(!(te instanceof MineralSmelterTileEntity)) return stacks;
((MineralSmelterTileEntity)te).reset_process(); ((MineralSmelterTileEntity)te).reset_process();
stacks.add(new ItemStack(this, 1)); stacks.add(new ItemStack(this, 1));
@ -125,21 +125,21 @@ public class EdMineralSmelter
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(player.isSneaking()) return ActionResultType.PASS; if(player.isShiftKeyDown()) return ActionResultType.PASS;
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
MineralSmelterTileEntity te = getTe(world, pos); MineralSmelterTileEntity te = getTe(world, pos);
if(te==null) return ActionResultType.FAIL; if(te==null) return ActionResultType.FAIL;
final ItemStack stack = player.getHeldItem(hand); final ItemStack stack = player.getItemInHand(hand);
boolean dirty = false; boolean dirty = false;
if(te.accepts_lava_container(stack)) { if(te.accepts_lava_container(stack)) {
if(stack.isItemEqualIgnoreDurability(MineralSmelterTileEntity.BUCKET_STACK)) { // check how this works with item capabilities or so if(stack.sameItemStackIgnoreDurability(MineralSmelterTileEntity.BUCKET_STACK)) { // check how this works with item capabilities or so
if(te.fluid_level() >= MineralSmelterTileEntity.MAX_BUCKET_EXTRACT_FLUID_LEVEL) { if(te.fluid_level() >= MineralSmelterTileEntity.MAX_BUCKET_EXTRACT_FLUID_LEVEL) {
if(stack.getCount() > 1) { if(stack.getCount() > 1) {
int target_stack_index = -1; int target_stack_index = -1;
for(int i=0; i<player.inventory.getSizeInventory(); ++i) { for(int i=0; i<player.inventory.getContainerSize(); ++i) {
if(player.inventory.getStackInSlot(i).isEmpty()) { if(player.inventory.getItem(i).isEmpty()) {
target_stack_index = i; target_stack_index = i;
break; break;
} }
@ -147,25 +147,25 @@ public class EdMineralSmelter
if(target_stack_index >= 0) { if(target_stack_index >= 0) {
te.reset_process(); te.reset_process();
stack.shrink(1); stack.shrink(1);
player.setHeldItem(hand, stack); player.setItemInHand(hand, stack);
player.inventory.setInventorySlotContents(target_stack_index, MineralSmelterTileEntity.LAVA_BUCKET_STACK.copy()); player.inventory.setItem(target_stack_index, MineralSmelterTileEntity.LAVA_BUCKET_STACK.copy());
world.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL_LAVA, SoundCategory.BLOCKS, 1f, 1f); world.playSound(null, pos, SoundEvents.BUCKET_FILL_LAVA, SoundCategory.BLOCKS, 1f, 1f);
dirty = true; dirty = true;
} }
} else { } else {
te.reset_process(); te.reset_process();
player.setHeldItem(hand, MineralSmelterTileEntity.LAVA_BUCKET_STACK.copy()); player.setItemInHand(hand, MineralSmelterTileEntity.LAVA_BUCKET_STACK.copy());
world.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL_LAVA, SoundCategory.BLOCKS, 1f, 1f); world.playSound(null, pos, SoundEvents.BUCKET_FILL_LAVA, SoundCategory.BLOCKS, 1f, 1f);
dirty = true; dirty = true;
} }
} }
} }
} else if(stack.isEmpty()) { } else if(stack.isEmpty()) {
final ItemStack istack = te.getStackInSlot(1).copy(); final ItemStack istack = te.getItem(1).copy();
if(te.phase() > MineralSmelterTileEntity.PHASE_WARMUP) player.setFire(1); if(te.phase() > MineralSmelterTileEntity.PHASE_WARMUP) player.setSecondsOnFire(1);
if(!istack.isEmpty()) { if(!istack.isEmpty()) {
istack.setCount(1); istack.setCount(1);
player.setHeldItem(hand, istack); player.setItemInHand(hand, istack);
te.reset_process(); te.reset_process();
dirty = true; dirty = true;
} }
@ -173,7 +173,7 @@ public class EdMineralSmelter
stack.shrink(1); stack.shrink(1);
dirty = true; dirty = true;
} }
if(dirty) player.inventory.markDirty(); if(dirty) player.inventory.setChanged();
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@ -183,7 +183,7 @@ public class EdMineralSmelter
{ {
if(state.getBlock()!=this) return; if(state.getBlock()!=this) return;
IParticleData particle = ParticleTypes.SMOKE; IParticleData particle = ParticleTypes.SMOKE;
switch(state.get(PHASE)) { switch(state.getValue(PHASE)) {
case MineralSmelterTileEntity.PHASE_WARMUP: case MineralSmelterTileEntity.PHASE_WARMUP:
return; return;
case MineralSmelterTileEntity.PHASE_HOT: case MineralSmelterTileEntity.PHASE_HOT:
@ -207,7 +207,7 @@ public class EdMineralSmelter
@Nullable @Nullable
private MineralSmelterTileEntity getTe(World world, BlockPos pos) private MineralSmelterTileEntity getTe(World world, BlockPos pos)
{ final TileEntity te=world.getTileEntity(pos); return (!(te instanceof MineralSmelterTileEntity)) ? (null) : ((MineralSmelterTileEntity)te); } { final TileEntity te=world.getBlockEntity(pos); return (!(te instanceof MineralSmelterTileEntity)) ? (null) : ((MineralSmelterTileEntity)te); }
} }
//-------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------
@ -231,8 +231,8 @@ public class EdMineralSmelter
private static final ItemStack BUCKET_STACK = new ItemStack(Items.BUCKET); private static final ItemStack BUCKET_STACK = new ItemStack(Items.BUCKET);
private static final ItemStack LAVA_BUCKET_STACK = new ItemStack(Items.LAVA_BUCKET); private static final ItemStack LAVA_BUCKET_STACK = new ItemStack(Items.LAVA_BUCKET);
private static final FluidStack LAVA_BUCKET_FLUID_STACK = new FluidStack(Fluids.LAVA, 1000); private static final FluidStack LAVA_BUCKET_FLUID_STACK = new FluidStack(Fluids.LAVA, 1000);
private static Set<Item> accepted_minerals = new HashSet<Item>(); private static final Set<Item> accepted_minerals = new HashSet<Item>();
private static Set<Item> accepted_lava_contrainers = new HashSet<Item>(); private static final Set<Item> accepted_lava_contrainers = new HashSet<Item>();
private static int energy_consumption = DEFAULT_ENERGY_CONSUMPTION; private static int energy_consumption = DEFAULT_ENERGY_CONSUMPTION;
private static int heatup_rate = DEFAULT_HEATUP_RATE; private static int heatup_rate = DEFAULT_HEATUP_RATE;
private static int cooldown_rate = 1; private static int cooldown_rate = 1;
@ -343,17 +343,17 @@ public class EdMineralSmelter
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt); return nbt; } { super.save(nbt); writenbt(nbt); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
energy_handler_.invalidate(); energy_handler_.invalidate();
fluid_handler_.invalidate(); fluid_handler_.invalidate();
item_handler_.invalidate(); item_handler_.invalidate();
@ -363,7 +363,7 @@ public class EdMineralSmelter
@Override @Override
public ITextComponent getName() public ITextComponent getName()
{ final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getTranslationKey() : "Lab furnace"); } { final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getDescriptionId() : "Lab furnace"); }
@Override @Override
public boolean hasCustomName() public boolean hasCustomName()
@ -376,7 +376,7 @@ public class EdMineralSmelter
// IInventory ------------------------------------------------------------------------------ // IInventory ------------------------------------------------------------------------------
@Override @Override
public int getSizeInventory() public int getContainerSize()
{ return stacks_.size(); } { return stacks_.size(); }
@Override @Override
@ -384,47 +384,47 @@ public class EdMineralSmelter
{ for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; } { for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; }
@Override @Override
public ItemStack getStackInSlot(int index) public ItemStack getItem(int index)
{ return ((index >= 0) && (index < getSizeInventory())) ? stacks_.get(index) : ItemStack.EMPTY; } { return ((index >= 0) && (index < getContainerSize())) ? stacks_.get(index) : ItemStack.EMPTY; }
@Override @Override
public ItemStack decrStackSize(int index, int count) public ItemStack removeItem(int index, int count)
{ return ItemStackHelper.getAndSplit(stacks_, index, count); } { return ItemStackHelper.removeItem(stacks_, index, count); }
@Override @Override
public ItemStack removeStackFromSlot(int index) public ItemStack removeItemNoUpdate(int index)
{ return ItemStackHelper.getAndRemove(stacks_, index); } { return ItemStackHelper.takeItem(stacks_, index); }
@Override @Override
public void setInventorySlotContents(int index, ItemStack stack) public void setItem(int index, ItemStack stack)
{ if(stack.getCount()>getInventoryStackLimit()){stack.setCount(getInventoryStackLimit());} stacks_.set(index, stack); markDirty(); } { if(stack.getCount()>getMaxStackSize()){stack.setCount(getMaxStackSize());} stacks_.set(index, stack); setChanged(); }
@Override @Override
public int getInventoryStackLimit() public int getMaxStackSize()
{ return 1; } { return 1; }
@Override @Override
public void markDirty() public void setChanged()
{ super.markDirty(); } { super.setChanged(); }
@Override @Override
public boolean isUsableByPlayer(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return ((getWorld().getTileEntity(getPos()) == this)) && (getPos().distanceSq(player.getPosition()) < 64); } { return ((getLevel().getBlockEntity(getBlockPos()) == this)) && (getBlockPos().distSqr(player.blockPosition()) < 64); }
@Override @Override
public void openInventory(PlayerEntity player) public void startOpen(PlayerEntity player)
{} {}
@Override @Override
public void closeInventory(PlayerEntity player) public void stopOpen(PlayerEntity player)
{ markDirty(); } { setChanged(); }
@Override @Override
public boolean isItemValidForSlot(int index, ItemStack stack) public boolean canPlaceItem(int index, ItemStack stack)
{ return ((index==0) && accepts_input(stack)) || (index==1); } { return ((index==0) && accepts_input(stack)) || (index==1); }
@Override @Override
public void clear() public void clearContent()
{ reset_process(); } { reset_process(); }
// ISidedInventory ---------------------------------------------------------------------------- // ISidedInventory ----------------------------------------------------------------------------
@ -436,20 +436,20 @@ public class EdMineralSmelter
{ return SIDED_INV_SLOTS; } { return SIDED_INV_SLOTS; }
@Override @Override
public boolean canInsertItem(int index, ItemStack stack, Direction direction) public boolean canPlaceItemThroughFace(int index, ItemStack stack, Direction direction)
{ return (index==0) && isItemValidForSlot(index, stack); } { return (index==0) && canPlaceItem(index, stack); }
@Override @Override
public boolean canExtractItem(int index, ItemStack stack, Direction direction) public boolean canTakeItemThroughFace(int index, ItemStack stack, Direction direction)
{ return (index==1) && (!stacks_.get(1).isEmpty()); } { return (index==1) && (!stacks_.get(1).isEmpty()); }
// IItemHandler -------------------------------------------------------------------------------- // IItemHandler --------------------------------------------------------------------------------
private LazyOptional<IItemHandler> item_handler_ = LazyOptional.of(() -> (IItemHandler)new BItemHandler(this)); private final LazyOptional<IItemHandler> item_handler_ = LazyOptional.of(() -> (IItemHandler)new BItemHandler(this));
protected static class BItemHandler implements IItemHandler protected static class BItemHandler implements IItemHandler
{ {
private MineralSmelterTileEntity te; private final MineralSmelterTileEntity te;
BItemHandler(MineralSmelterTileEntity te) BItemHandler(MineralSmelterTileEntity te)
{ this.te = te; } { this.te = te; }
@ -460,11 +460,11 @@ public class EdMineralSmelter
@Override @Override
public int getSlotLimit(int index) public int getSlotLimit(int index)
{ return te.getInventoryStackLimit(); } { return te.getMaxStackSize(); }
@Override @Override
public boolean isItemValid(int slot, @Nonnull ItemStack stack) public boolean isItemValid(int slot, @Nonnull ItemStack stack)
{ return te.isItemValidForSlot(slot, stack); } { return te.canPlaceItem(slot, stack); }
@Override @Override
@Nonnull @Nonnull
@ -484,12 +484,12 @@ public class EdMineralSmelter
@Override @Override
@Nonnull @Nonnull
public ItemStack getStackInSlot(int index) public ItemStack getStackInSlot(int index)
{ return te.getStackInSlot(index); } { return te.getItem(index); }
} }
// IFluidHandler -------------------------------------------------------------------------------- // IFluidHandler --------------------------------------------------------------------------------
private LazyOptional<IFluidHandler> fluid_handler_ = LazyOptional.of(() -> (IFluidHandler)new BFluidHandler(this)); private final LazyOptional<IFluidHandler> fluid_handler_ = LazyOptional.of(() -> (IFluidHandler)new BFluidHandler(this));
private static class BFluidHandler implements IFluidHandler private static class BFluidHandler implements IFluidHandler
{ {
@ -548,7 +548,7 @@ public class EdMineralSmelter
if(energy_stored_ >= MAX_ENERGY_BUFFER) return 0; if(energy_stored_ >= MAX_ENERGY_BUFFER) return 0;
int n = Math.min(maxReceive, (MAX_ENERGY_BUFFER - energy_stored_)); int n = Math.min(maxReceive, (MAX_ENERGY_BUFFER - energy_stored_));
if(n > MAX_ENERGY_TRANSFER) n = MAX_ENERGY_TRANSFER; if(n > MAX_ENERGY_TRANSFER) n = MAX_ENERGY_TRANSFER;
if(!simulate) {energy_stored_ += n; markDirty(); } if(!simulate) {energy_stored_ += n; setChanged(); }
return n; return n;
} }
@ -568,17 +568,17 @@ public class EdMineralSmelter
@Override @Override
public void tick() public void tick()
{ {
if(world.isRemote) return; if(level.isClientSide) return;
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
BlockState state = world.getBlockState(pos); BlockState state = level.getBlockState(worldPosition);
if(!(state.getBlock() instanceof MineralSmelterBlock)) return; if(!(state.getBlock() instanceof MineralSmelterBlock)) return;
boolean dirty = false; boolean dirty = false;
final int last_phase = phase(); final int last_phase = phase();
final ItemStack istack = stacks_.get(0); final ItemStack istack = stacks_.get(0);
if(istack.isEmpty() && (fluid_level()==0)) { if(istack.isEmpty() && (fluid_level()==0)) {
progress_ = 0; progress_ = 0;
} else if((energy_stored_ <= 0) || (world.isBlockPowered(pos))) { } else if((energy_stored_ <= 0) || (level.hasNeighborSignal(worldPosition))) {
progress_ = MathHelper.clamp(progress_-cooldown_rate, 0,100); progress_ = MathHelper.clamp(progress_-cooldown_rate, 0,100);
} else if(progress_ >= 100) { } else if(progress_ >= 100) {
progress_ = 100; progress_ = 100;
@ -592,11 +592,11 @@ public class EdMineralSmelter
if(is_lava_container || (new_phase != last_phase)) { if(is_lava_container || (new_phase != last_phase)) {
if(is_lava_container) { if(is_lava_container) {
// That stays in the slot until its extracted or somone takes it out. // That stays in the slot until its extracted or somone takes it out.
if(istack.isItemEqual(BUCKET_STACK)) { if(istack.sameItem(BUCKET_STACK)) {
if(!stacks_.get(1).isItemEqual(LAVA_BUCKET_STACK)) { if(!stacks_.get(1).sameItem(LAVA_BUCKET_STACK)) {
if(fluid_level() >= MAX_BUCKET_EXTRACT_FLUID_LEVEL) { if(fluid_level() >= MAX_BUCKET_EXTRACT_FLUID_LEVEL) {
stacks_.set(1, LAVA_BUCKET_STACK); stacks_.set(1, LAVA_BUCKET_STACK);
world.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL_LAVA, SoundCategory.BLOCKS, 0.2f, 1.3f); level.playSound(null, worldPosition, SoundEvents.BUCKET_FILL_LAVA, SoundCategory.BLOCKS, 0.2f, 1.3f);
} else { } else {
stacks_.set(1, istack.copy()); stacks_.set(1, istack.copy());
} }
@ -612,16 +612,16 @@ public class EdMineralSmelter
fluid_level_ = MAX_FLUID_LEVEL; fluid_level_ = MAX_FLUID_LEVEL;
stacks_.set(1, ItemStack.EMPTY); stacks_.set(1, ItemStack.EMPTY);
stacks_.set(0, ItemStack.EMPTY); stacks_.set(0, ItemStack.EMPTY);
world.playSound(null, pos, SoundEvents.BLOCK_LAVA_AMBIENT, SoundCategory.BLOCKS, 0.2f, 1.0f); level.playSound(null, worldPosition, SoundEvents.LAVA_AMBIENT, SoundCategory.BLOCKS, 0.2f, 1.0f);
dirty = true; dirty = true;
break; break;
case PHASE_MAGMABLOCK: case PHASE_MAGMABLOCK:
stacks_.set(1, MAGMA_STACK.copy()); stacks_.set(1, MAGMA_STACK.copy());
world.playSound(null, pos, SoundEvents.BLOCK_FIRE_AMBIENT, SoundCategory.BLOCKS, 0.2f, 0.8f); level.playSound(null, worldPosition, SoundEvents.FIRE_AMBIENT, SoundCategory.BLOCKS, 0.2f, 0.8f);
dirty = true; dirty = true;
break; break;
case PHASE_HOT: case PHASE_HOT:
world.playSound(null, pos, SoundEvents.BLOCK_FIRE_AMBIENT, SoundCategory.BLOCKS, 0.2f, 0.8f); level.playSound(null, worldPosition, SoundEvents.FIRE_AMBIENT, SoundCategory.BLOCKS, 0.2f, 0.8f);
break; break;
} }
} else { } else {
@ -630,45 +630,45 @@ public class EdMineralSmelter
stacks_.set(0, (fluid_level_ >= MAX_BUCKET_EXTRACT_FLUID_LEVEL) ? (MAGMA_STACK.copy()) : (ItemStack.EMPTY)); stacks_.set(0, (fluid_level_ >= MAX_BUCKET_EXTRACT_FLUID_LEVEL) ? (MAGMA_STACK.copy()) : (ItemStack.EMPTY));
stacks_.set(1, stacks_.get(0).copy()); stacks_.set(1, stacks_.get(0).copy());
fluid_level_ = 0; fluid_level_ = 0;
world.playSound(null, pos, SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.5f, 1.1f); level.playSound(null, worldPosition, SoundEvents.LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.5f, 1.1f);
dirty = true; dirty = true;
break; break;
case PHASE_HOT: case PHASE_HOT:
if(istack.isItemEqual(MAGMA_STACK)) { if(istack.sameItem(MAGMA_STACK)) {
stacks_.set(1, new ItemStack(Blocks.OBSIDIAN)); stacks_.set(1, new ItemStack(Blocks.OBSIDIAN));
} else { } else {
stacks_.set(1, new ItemStack(Blocks.COBBLESTONE)); stacks_.set(1, new ItemStack(Blocks.COBBLESTONE));
} }
world.playSound(null, pos, SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.3f, 0.9f); level.playSound(null, worldPosition, SoundEvents.LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.3f, 0.9f);
dirty = true; dirty = true;
break; break;
case PHASE_WARMUP: case PHASE_WARMUP:
world.playSound(null, pos, SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.3f, 0.7f); level.playSound(null, worldPosition, SoundEvents.LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.3f, 0.7f);
break; break;
} }
} }
} else if((phase()==PHASE_LAVA) && (fluid_level() >= MAX_BUCKET_EXTRACT_FLUID_LEVEL)) { } else if((phase()==PHASE_LAVA) && (fluid_level() >= MAX_BUCKET_EXTRACT_FLUID_LEVEL)) {
// Fluid transfer check // Fluid transfer check
final IFluidHandler fh = FluidUtil.getFluidHandler(world, getPos().down(), Direction.UP).orElse(null); final IFluidHandler fh = FluidUtil.getFluidHandler(level, getBlockPos().below(), Direction.UP).orElse(null);
if(fh != null) { if(fh != null) {
int n = fh.fill(LAVA_BUCKET_FLUID_STACK.copy(), FluidAction.SIMULATE); int n = fh.fill(LAVA_BUCKET_FLUID_STACK.copy(), FluidAction.SIMULATE);
if(n >= LAVA_BUCKET_FLUID_STACK.getAmount()/2) { if(n >= LAVA_BUCKET_FLUID_STACK.getAmount()/2) {
n = fh.fill(LAVA_BUCKET_FLUID_STACK.copy(), FluidAction.EXECUTE); n = fh.fill(LAVA_BUCKET_FLUID_STACK.copy(), FluidAction.EXECUTE);
if(n > 0) { if(n > 0) {
reset_process(); reset_process();
world.playSound(null, pos, SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.3f, 0.7f); level.playSound(null, worldPosition, SoundEvents.LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.3f, 0.7f);
} }
} }
} }
} }
// Block state // Block state
if((force_block_update_ || (state.get(MineralSmelterBlock.PHASE) != new_phase))) { if((force_block_update_ || (state.getValue(MineralSmelterBlock.PHASE) != new_phase))) {
state = state.with(MineralSmelterBlock.PHASE, new_phase); state = state.setValue(MineralSmelterBlock.PHASE, new_phase);
world.setBlockState(pos, state,3|16); level.setBlock(worldPosition, state,3|16);
world.notifyNeighborsOfStateChange(getPos(), state.getBlock()); level.updateNeighborsAt(getBlockPos(), state.getBlock());
force_block_update_ = false; force_block_update_ = false;
} }
if(dirty) markDirty(); if(dirty) setChanged();
} }
} }
} }

View file

@ -15,6 +15,7 @@ import net.minecraft.world.World;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.state.BooleanProperty; import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer; import net.minecraft.state.StateContainer;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.tileentity.TileEntityType; import net.minecraft.tileentity.TileEntityType;
@ -41,6 +42,7 @@ import wile.engineersdecor.ModContent;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class EdPipeValve public class EdPipeValve
{ {
public static final int CFG_CHECK_VALVE = 0x1; public static final int CFG_CHECK_VALVE = 0x1;
@ -69,28 +71,28 @@ public class EdPipeValve
public final int valve_config; public final int valve_config;
public PipeValveBlock(long config, int valve_config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABB) public PipeValveBlock(long config, int valve_config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABB)
{ super(config, builder, unrotatedAABB); this.valve_config = valve_config; } { super(config, builder, unrotatedAABB); this.valve_config = valve_config; }
private BlockState get_rsconnector_state(BlockState state, IWorld world, BlockPos pos, @Nullable BlockPos fromPos) private BlockState get_rsconnector_state(BlockState state, IWorld world, BlockPos pos, @Nullable BlockPos fromPos)
{ {
if((valve_config & (CFG_REDSTONE_CONTROLLED_VALVE))==0) return state; if((valve_config & (CFG_REDSTONE_CONTROLLED_VALVE))==0) return state;
Direction.Axis bfa = state.get(FACING).getAxis(); Direction.Axis bfa = state.getValue(FACING).getAxis();
for(Direction f:Direction.values()) { for(Direction f:Direction.values()) {
boolean cn = (f.getAxis() != bfa); boolean cn = (f.getAxis() != bfa);
if(cn) { if(cn) {
BlockPos nbp = pos.offset(f); BlockPos nbp = pos.relative(f);
if((fromPos != null) && (!nbp.equals(fromPos))) continue; // do not change connectors except form the frompos. if((fromPos != null) && (!nbp.equals(fromPos))) continue; // do not change connectors except form the frompos.
BlockState nbs = world.getBlockState(nbp); BlockState nbs = world.getBlockState(nbp);
if((nbs.getBlock() instanceof PipeValveBlock) || ((!nbs.canProvidePower()) && (!nbs.canConnectRedstone(world, nbp, f.getOpposite())))) cn = false; if((nbs.getBlock() instanceof PipeValveBlock) || ((!nbs.isSignalSource()) && (!nbs.canConnectRedstone(world, nbp, f.getOpposite())))) cn = false;
} }
switch(f) { switch(f) {
case NORTH: state = state.with(RS_CN_N, cn); break; case NORTH: state = state.setValue(RS_CN_N, cn); break;
case SOUTH: state = state.with(RS_CN_S, cn); break; case SOUTH: state = state.setValue(RS_CN_S, cn); break;
case EAST: state = state.with(RS_CN_E, cn); break; case EAST: state = state.setValue(RS_CN_E, cn); break;
case WEST: state = state.with(RS_CN_W, cn); break; case WEST: state = state.setValue(RS_CN_W, cn); break;
case UP: state = state.with(RS_CN_U, cn); break; case UP: state = state.setValue(RS_CN_U, cn); break;
case DOWN: state = state.with(RS_CN_D, cn); break; case DOWN: state = state.setValue(RS_CN_D, cn); break;
} }
} }
return state; return state;
@ -98,28 +100,28 @@ public class EdPipeValve
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return VoxelShapes.fullCube(); } { return VoxelShapes.block(); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(RS_CN_N, RS_CN_S, RS_CN_E, RS_CN_W, RS_CN_U, RS_CN_D); } { super.createBlockStateDefinition(builder); builder.add(RS_CN_N, RS_CN_S, RS_CN_E, RS_CN_W, RS_CN_U, RS_CN_D); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
return super.getStateForPlacement(context).with(RS_CN_N, false).with(RS_CN_S, false).with(RS_CN_E, false) return super.getStateForPlacement(context).setValue(RS_CN_N, false).setValue(RS_CN_S, false).setValue(RS_CN_E, false)
.with(RS_CN_W, false).with(RS_CN_U, false).with(RS_CN_D, false); .setValue(RS_CN_W, false).setValue(RS_CN_U, false).setValue(RS_CN_D, false);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState updatePostPlacement(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos) public BlockState updateShape(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos)
{ return get_rsconnector_state(state, world, pos, null); } { return get_rsconnector_state(state, world, pos, null); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ world.notifyNeighborsOfStateChange(pos,this); } { world.updateNeighborsAt(pos,this); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -136,7 +138,7 @@ public class EdPipeValve
@Override @Override
public boolean canConnectRedstone(BlockState state, IBlockReader world, BlockPos pos, @Nullable Direction side) public boolean canConnectRedstone(BlockState state, IBlockReader world, BlockPos pos, @Nullable Direction side)
{ return (side!=null) && (side!=state.get(FACING)) && (side!=state.get(FACING).getOpposite()); } { return (side!=null) && (side!=state.getValue(FACING)) && (side!=state.getValue(FACING).getOpposite()); }
@Override @Override
public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side) public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
@ -144,17 +146,17 @@ public class EdPipeValve
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean canProvidePower(BlockState state) public boolean isSignalSource(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getWeakPower(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side) public int getSignal(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side)
{ return 0; } { return 0; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getStrongPower(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side) public int getDirectSignal(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side)
{ return 0; } { return 0; }
} }
@ -178,14 +180,14 @@ public class EdPipeValve
private Direction block_facing() private Direction block_facing()
{ {
BlockState st = getWorld().getBlockState(getPos()); BlockState st = getLevel().getBlockState(getBlockPos());
return (st.getBlock() instanceof PipeValveBlock) ? st.get(PipeValveBlock.FACING) : Direction.NORTH; return (st.getBlock() instanceof PipeValveBlock) ? st.getValue(PipeValveBlock.FACING) : Direction.NORTH;
} }
private long valve_config() private long valve_config()
{ {
if(valve_config_ <= 0) { if(valve_config_ <= 0) {
final Block block = getWorld().getBlockState(getPos()).getBlock(); final Block block = getLevel().getBlockState(getBlockPos()).getBlock();
if(block instanceof PipeValveBlock) valve_config_ = ((PipeValveBlock)block).valve_config; if(block instanceof PipeValveBlock) valve_config_ = ((PipeValveBlock)block).valve_config;
} }
return valve_config_; return valve_config_;
@ -194,17 +196,17 @@ public class EdPipeValve
// TileEntity ----------------------------------------------------------------------------- // TileEntity -----------------------------------------------------------------------------
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
back_flow_handler_.invalidate(); back_flow_handler_.invalidate();
fluid_handler_.invalidate(); fluid_handler_.invalidate();
} }
// ICapabilityProvider -------------------------------------------------------------------- // ICapabilityProvider --------------------------------------------------------------------
private LazyOptional<IFluidHandler> back_flow_handler_ = LazyOptional.of(() -> (IFluidHandler)new BackFlowHandler()); private final LazyOptional<IFluidHandler> back_flow_handler_ = LazyOptional.of(() -> (IFluidHandler)new BackFlowHandler());
private LazyOptional<IFluidHandler> fluid_handler_ = LazyOptional.of(() -> (IFluidHandler)new MainFlowHandler(this)); private final LazyOptional<IFluidHandler> fluid_handler_ = LazyOptional.of(() -> (IFluidHandler)new MainFlowHandler(this));
@Override @Override
public <T> LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable Direction facing) public <T> LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable Direction facing)
@ -223,7 +225,7 @@ public class EdPipeValve
@Nullable @Nullable
private IFluidHandler forward_fluid_handler() private IFluidHandler forward_fluid_handler()
{ {
final TileEntity te = world.getTileEntity(pos.offset(block_facing())); final TileEntity te = level.getBlockEntity(worldPosition.relative(block_facing()));
if(te == null) return null; if(te == null) return null;
return te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, block_facing().getOpposite()).orElse(null); return te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, block_facing().getOpposite()).orElse(null);
} }
@ -232,7 +234,7 @@ public class EdPipeValve
private static class MainFlowHandler implements IFluidHandler private static class MainFlowHandler implements IFluidHandler
{ {
private PipeValveTileEntity te; private final PipeValveTileEntity te;
public MainFlowHandler(PipeValveTileEntity te) { this.te = te; } public MainFlowHandler(PipeValveTileEntity te) { this.te = te; }
@Override public int getTanks() { return 1; } @Override public int getTanks() { return 1; }
@Override public FluidStack getFluidInTank(int tank) { return FluidStack.EMPTY; } @Override public FluidStack getFluidInTank(int tank) { return FluidStack.EMPTY; }
@ -248,7 +250,7 @@ public class EdPipeValve
if(fh==null) return 0; if(fh==null) return 0;
FluidStack res = resource.copy(); FluidStack res = resource.copy();
if((te.valve_config() & CFG_REDSTONE_CONTROLLED_VALVE) != 0) { if((te.valve_config() & CFG_REDSTONE_CONTROLLED_VALVE) != 0) {
int rs = te.world.getRedstonePowerFromNeighbors(te.pos); int rs = te.level.getBestNeighborSignal(te.worldPosition);
if(rs <= 0) return 0; if(rs <= 0) return 0;
if(((te.valve_config() & CFG_ANALOG_VALVE) != 0) && (rs < 15)) res.setAmount(MathHelper.clamp(rs * redstone_flow_slope_mb, 1, res.getAmount())); if(((te.valve_config() & CFG_ANALOG_VALVE) != 0) && (rs < 15)) res.setAmount(MathHelper.clamp(rs * redstone_flow_slope_mb, 1, res.getAmount()));
} }

View file

@ -77,22 +77,22 @@ public class EdPlacer
public static class PlacerBlock extends DecorBlock.Directed implements IDecorBlock public static class PlacerBlock extends DecorBlock.Directed implements IDecorBlock
{ {
public PlacerBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABB) public PlacerBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return VoxelShapes.fullCube(); } { return VoxelShapes.block(); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState blockState, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState blockState, World world, BlockPos pos)
{ return Container.calcRedstone(world.getTileEntity(pos)); } { return Container.getRedstoneSignalFromBlockEntity(world.getBlockEntity(pos)); }
@Override @Override
public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side) public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
@ -108,17 +108,17 @@ public class EdPlacer
{ return new PlacerTileEntity(); } { return new PlacerTileEntity(); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
if(world.isRemote) return; if(world.isClientSide) return;
if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return; if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return;
CompoundNBT te_nbt = stack.getTag().getCompound("tedata"); CompoundNBT te_nbt = stack.getTag().getCompound("tedata");
if(te_nbt.isEmpty()) return; if(te_nbt.isEmpty()) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof PlacerTileEntity)) return; if(!(te instanceof PlacerTileEntity)) return;
((PlacerTileEntity)te).readnbt(te_nbt, false); ((PlacerTileEntity)te).readnbt(te_nbt, false);
((PlacerTileEntity)te).reset_rtstate(); ((PlacerTileEntity)te).reset_rtstate();
((PlacerTileEntity)te).markDirty(); ((PlacerTileEntity)te).setChanged();
} }
@Override @Override
@ -129,7 +129,7 @@ public class EdPlacer
public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof PlacerTileEntity)) return stacks; if(!(te instanceof PlacerTileEntity)) return stacks;
if(!explosion) { if(!explosion) {
ItemStack stack = new ItemStack(this, 1); ItemStack stack = new ItemStack(this, 1);
@ -151,10 +151,10 @@ public class EdPlacer
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof PlacerTileEntity)) return ActionResultType.FAIL; if(!(te instanceof PlacerTileEntity)) return ActionResultType.FAIL;
if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL; if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL;
NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te); NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te);
@ -165,25 +165,25 @@ public class EdPlacer
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean unused)
{ {
if(!(world instanceof World) || (((World) world).isRemote)) return; if(!(world instanceof World) || (((World) world).isClientSide)) return;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof PlacerTileEntity)) return; if(!(te instanceof PlacerTileEntity)) return;
((PlacerTileEntity)te).block_updated(); ((PlacerTileEntity)te).block_updated();
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean canProvidePower(BlockState state) public boolean isSignalSource(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getWeakPower(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side) public int getSignal(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side)
{ return 0; } { return 0; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getStrongPower(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side) public int getDirectSignal(BlockState blockState, IBlockReader blockAccess, BlockPos pos, Direction side)
{ return 0; } { return 0; }
} }
@ -255,7 +255,7 @@ public class EdPlacer
public void block_updated() public void block_updated()
{ {
boolean powered = world.isBlockPowered(pos); boolean powered = level.hasNeighborSignal(worldPosition);
if(block_power_signal_ != powered) block_power_updated_ = true; if(block_power_signal_ != powered) block_power_updated_ = true;
block_power_signal_ = powered; block_power_signal_ = powered;
if(block_power_updated_) { if(block_power_updated_) {
@ -271,17 +271,17 @@ public class EdPlacer
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt, false); } { super.load(state, nbt); readnbt(nbt, false); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt, false); return nbt; } { super.save(nbt); writenbt(nbt, false); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
Arrays.stream(item_handlers).forEach(LazyOptional::invalidate); Arrays.stream(item_handlers).forEach(LazyOptional::invalidate);
} }
@ -289,7 +289,7 @@ public class EdPlacer
@Override @Override
public ITextComponent getName() public ITextComponent getName()
{ final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getTranslationKey() : "Factory placer"); } { final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getDescriptionId() : "Factory placer"); }
@Override @Override
public boolean hasCustomName() public boolean hasCustomName()
@ -307,12 +307,12 @@ public class EdPlacer
@Override @Override
public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player ) public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player )
{ return new PlacerContainer(id, inventory, this, IWorldPosCallable.of(world, pos), fields); } { return new PlacerContainer(id, inventory, this, IWorldPosCallable.create(level, worldPosition), fields); }
// IInventory ------------------------------------------------------------------------------------------- // IInventory -------------------------------------------------------------------------------------------
@Override @Override
public int getSizeInventory() public int getContainerSize()
{ return stacks_.size(); } { return stacks_.size(); }
@Override @Override
@ -320,53 +320,53 @@ public class EdPlacer
{ for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; } { for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; }
@Override @Override
public ItemStack getStackInSlot(int index) public ItemStack getItem(int index)
{ return (index < getSizeInventory()) ? stacks_.get(index) : ItemStack.EMPTY; } { return (index < getContainerSize()) ? stacks_.get(index) : ItemStack.EMPTY; }
@Override @Override
public ItemStack decrStackSize(int index, int count) public ItemStack removeItem(int index, int count)
{ return ItemStackHelper.getAndSplit(stacks_, index, count); } { return ItemStackHelper.removeItem(stacks_, index, count); }
@Override @Override
public ItemStack removeStackFromSlot(int index) public ItemStack removeItemNoUpdate(int index)
{ return ItemStackHelper.getAndRemove(stacks_, index); } { return ItemStackHelper.takeItem(stacks_, index); }
@Override @Override
public void setInventorySlotContents(int index, ItemStack stack) public void setItem(int index, ItemStack stack)
{ {
if((index<0) || (index >= NUM_OF_SLOTS)) return; if((index<0) || (index >= NUM_OF_SLOTS)) return;
stacks_.set(index, stack); stacks_.set(index, stack);
if(stack.getCount() > getInventoryStackLimit()) stack.setCount(getInventoryStackLimit()); if(stack.getCount() > getMaxStackSize()) stack.setCount(getMaxStackSize());
if(tick_timer_ > 8) tick_timer_ = 8; if(tick_timer_ > 8) tick_timer_ = 8;
markDirty(); setChanged();
} }
@Override @Override
public int getInventoryStackLimit() public int getMaxStackSize()
{ return 64; } { return 64; }
@Override @Override
public void markDirty() public void setChanged()
{ super.markDirty(); } { super.setChanged(); }
@Override @Override
public boolean isUsableByPlayer(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return ((getWorld().getTileEntity(getPos()) == this)) && (getPos().distanceSq(player.getPosition()) < 64); } { return ((getLevel().getBlockEntity(getBlockPos()) == this)) && (getBlockPos().distSqr(player.blockPosition()) < 64); }
@Override @Override
public void openInventory(PlayerEntity player) public void startOpen(PlayerEntity player)
{} {}
@Override @Override
public void closeInventory(PlayerEntity player) public void stopOpen(PlayerEntity player)
{ markDirty(); } { setChanged(); }
@Override @Override
public boolean isItemValidForSlot(int index, ItemStack stack) public boolean canPlaceItem(int index, ItemStack stack)
{ return (index>=0) && (index<NUM_OF_SLOTS); } { return (index>=0) && (index<NUM_OF_SLOTS); }
@Override @Override
public void clear() public void clearContent()
{ for(int i=0; i<stacks_.size(); ++i) stacks_.set(i, ItemStack.EMPTY); } // should search a better vectorizing method here. { for(int i=0; i<stacks_.size(); ++i) stacks_.set(i, ItemStack.EMPTY); } // should search a better vectorizing method here.
// Fields ----------------------------------------------------------------------------------------------- // Fields -----------------------------------------------------------------------------------------------
@ -409,11 +409,11 @@ public class EdPlacer
{ return SIDED_INV_SLOTS; } { return SIDED_INV_SLOTS; }
@Override @Override
public boolean canInsertItem(int index, ItemStack stack, Direction direction) public boolean canPlaceItemThroughFace(int index, ItemStack stack, Direction direction)
{ return is_input_slot(index) && isItemValidForSlot(index, stack); } { return is_input_slot(index) && canPlaceItem(index, stack); }
@Override @Override
public boolean canExtractItem(int index, ItemStack stack, Direction direction) public boolean canTakeItemThroughFace(int index, ItemStack stack, Direction direction)
{ return false; } { return false; }
// Capability export ------------------------------------------------------------------------------------ // Capability export ------------------------------------------------------------------------------------
@ -445,10 +445,10 @@ public class EdPlacer
stacks_.set(current_slot_index_, ItemStack.EMPTY); stacks_.set(current_slot_index_, ItemStack.EMPTY);
} }
for(int i=0; i<8; ++i) { for(int i=0; i<8; ++i) {
BlockPos p = pos.offset(facing, i); BlockPos p = worldPosition.relative(facing, i);
if(!world.isAirBlock(p)) continue; if(!level.isEmptyBlock(p)) continue;
world.addEntity(new ItemEntity(world, (p.getX()+0.5), (p.getY()+0.5), (p.getZ()+0.5), drop)); level.addFreshEntity(new ItemEntity(level, (p.getX()+0.5), (p.getY()+0.5), (p.getZ()+0.5), drop));
world.playSound(null, p, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.BLOCKS, 0.7f, 0.8f); level.playSound(null, p, SoundEvents.ITEM_PICKUP, SoundCategory.BLOCKS, 0.7f, 0.8f);
break; break;
} }
return true; return true;
@ -456,9 +456,9 @@ public class EdPlacer
private boolean try_place(Direction facing, boolean triggered) private boolean try_place(Direction facing, boolean triggered)
{ {
if(world.isRemote()) return false; if(level.isClientSide()) return false;
BlockPos placement_pos = pos.offset(facing); BlockPos placement_pos = worldPosition.relative(facing);
if(world.getTileEntity(placement_pos) != null) return false; if(level.getBlockEntity(placement_pos) != null) return false;
ItemStack current_stack = ItemStack.EMPTY; ItemStack current_stack = ItemStack.EMPTY;
for(int i=0; i<NUM_OF_SLOTS; ++i) { for(int i=0; i<NUM_OF_SLOTS; ++i) {
if(current_slot_index_ >= NUM_OF_SLOTS) current_slot_index_ = 0; if(current_slot_index_ >= NUM_OF_SLOTS) current_slot_index_ = 0;
@ -469,7 +469,7 @@ public class EdPlacer
if(current_stack.isEmpty()) { current_slot_index_ = 0; return false; } if(current_stack.isEmpty()) { current_slot_index_ = 0; return false; }
boolean no_space = false; boolean no_space = false;
final Item item = current_stack.getItem(); final Item item = current_stack.getItem();
Block block = Block.getBlockFromItem(item); Block block = Block.byItem(item);
if(block == Blocks.AIR) { if(block == Blocks.AIR) {
if(item != null) { if(item != null) {
Auxiliaries.logDebug("Placer spit: No block for item " + item.getRegistryName().toString()); Auxiliaries.logDebug("Placer spit: No block for item " + item.getRegistryName().toString());
@ -478,46 +478,46 @@ public class EdPlacer
// try next slot // try next slot
} }
} else if(block instanceof IPlantable) { } else if(block instanceof IPlantable) {
if(world.isAirBlock(placement_pos)) { if(level.isEmptyBlock(placement_pos)) {
// plant here, block below has to be valid soil. // plant here, block below has to be valid soil.
BlockState soilstate = world.getBlockState(placement_pos.down()); BlockState soilstate = level.getBlockState(placement_pos.below());
if(!soilstate.getBlock().canSustainPlant(soilstate, world, pos, Direction.UP, (IPlantable)block)) { if(!soilstate.getBlock().canSustainPlant(soilstate, level, worldPosition, Direction.UP, (IPlantable)block)) {
block = Blocks.AIR; block = Blocks.AIR;
} }
} else { } else {
// adjacent block is the soil, plant above if the soil is valid. // adjacent block is the soil, plant above if the soil is valid.
BlockState soilstate = world.getBlockState(placement_pos); BlockState soilstate = level.getBlockState(placement_pos);
if(soilstate.getBlock() == block) { if(soilstate.getBlock() == block) {
// The plant is already planted from the case above. // The plant is already planted from the case above.
block = Blocks.AIR; block = Blocks.AIR;
no_space = true; no_space = true;
} else if(!world.isAirBlock(placement_pos.up())) { } else if(!level.isEmptyBlock(placement_pos.above())) {
// If this is the soil an air block is needed above, if that is blocked we can't plant. // If this is the soil an air block is needed above, if that is blocked we can't plant.
block = Blocks.AIR; block = Blocks.AIR;
no_space = true; no_space = true;
} else if(!soilstate.getBlock().canSustainPlant(soilstate, world, pos, Direction.UP, (IPlantable)block)) { } else if(!soilstate.getBlock().canSustainPlant(soilstate, level, worldPosition, Direction.UP, (IPlantable)block)) {
// Would be space above, but it's not the right soil for the plant. // Would be space above, but it's not the right soil for the plant.
block = Blocks.AIR; block = Blocks.AIR;
} else { } else {
// Ok, plant above. // Ok, plant above.
placement_pos = placement_pos.up(); placement_pos = placement_pos.above();
} }
} }
} else { } else {
final BlockState current_placement_pos_state = world.getBlockState(placement_pos); final BlockState current_placement_pos_state = level.getBlockState(placement_pos);
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
final boolean replacable = (current_placement_pos_state.getBlock().isReplaceable(current_placement_pos_state, Fluids.EMPTY)) && ( final boolean replacable = (current_placement_pos_state.getBlock().canBeReplaced(current_placement_pos_state, Fluids.EMPTY)) && (
world.isAirBlock(placement_pos) || level.isEmptyBlock(placement_pos) ||
(current_placement_pos_state.getBlock() instanceof FlowingFluidBlock) || (current_placement_pos_state.getBlock() instanceof FlowingFluidBlock) ||
(current_placement_pos_state.getMaterial().isReplaceable() && (!current_placement_pos_state.getMaterial().isSolid())) (current_placement_pos_state.getMaterial().isReplaceable() && (!current_placement_pos_state.getMaterial().isSolid()))
); );
if((!replacable) || ( if((!replacable) || (
(!world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(placement_pos), (Entity e)->{ (!level.getEntitiesOfClass(Entity.class, new AxisAlignedBB(placement_pos), (Entity e)->{
if(e.canBeCollidedWith()) return true; if(e.isPickable()) return true;
if(triggered) return false; if(triggered) return false;
if((e instanceof ItemEntity)) { if((e instanceof ItemEntity)) {
if((e.getMotion().getY() > 0) || (e.getMotion().getY() < -0.5)) return true; // not falling or falling by if((e.getDeltaMovement().y() > 0) || (e.getDeltaMovement().y() < -0.5)) return true; // not falling or falling by
if(Math.abs(e.getMotion().getX())+Math.abs(e.getMotion().getZ()) > 0) return true; // not straight if(Math.abs(e.getDeltaMovement().x())+Math.abs(e.getDeltaMovement().z()) > 0) return true; // not straight
} }
return false; return false;
}).isEmpty()) }).isEmpty())
@ -531,44 +531,44 @@ public class EdPlacer
try { try {
BlockItemUseContext use_context = null; BlockItemUseContext use_context = null;
{ {
final FakePlayer placer = net.minecraftforge.common.util.FakePlayerFactory.getMinecraft((ServerWorld)world); final FakePlayer placer = net.minecraftforge.common.util.FakePlayerFactory.getMinecraft((ServerWorld)level);
if(placer != null) { if(placer != null) {
ItemStack placement_stack = current_stack.copy(); ItemStack placement_stack = current_stack.copy();
placement_stack.setCount(1); placement_stack.setCount(1);
ItemStack held = placer.getHeldItem(Hand.MAIN_HAND); ItemStack held = placer.getItemInHand(Hand.MAIN_HAND);
placer.setHeldItem(Hand.MAIN_HAND, placement_stack); placer.setItemInHand(Hand.MAIN_HAND, placement_stack);
List<Direction> directions = new ArrayList<>(Arrays.asList(Direction.UP, facing.getOpposite())); List<Direction> directions = new ArrayList<>(Arrays.asList(Direction.UP, facing.getOpposite()));
for(Direction d:Direction.values()) if(!directions.contains(d)) directions.add(d); for(Direction d:Direction.values()) if(!directions.contains(d)) directions.add(d);
for(Direction d:directions) { for(Direction d:directions) {
Vector3d v = Vector3d.copyCentered(placement_pos).subtract(Vector3d.copy(d.getDirectionVec())); Vector3d v = Vector3d.atCenterOf(placement_pos).subtract(Vector3d.atLowerCornerOf(d.getNormal()));
use_context = new BlockItemUseContext(new ItemUseContext(placer, Hand.MAIN_HAND, new BlockRayTraceResult(v, d, placement_pos, false))); use_context = new BlockItemUseContext(new ItemUseContext(placer, Hand.MAIN_HAND, new BlockRayTraceResult(v, d, placement_pos, false)));
if(block.getStateForPlacement(use_context) == null) use_context = null; if(block.getStateForPlacement(use_context) == null) use_context = null;
if(use_context!=null) break; if(use_context!=null) break;
} }
placer.setHeldItem(Hand.MAIN_HAND, held); placer.setItemInHand(Hand.MAIN_HAND, held);
} }
} }
BlockState placement_state = (use_context==null) ? (block.getDefaultState()) : (block.getStateForPlacement(use_context)); BlockState placement_state = (use_context==null) ? (block.defaultBlockState()) : (block.getStateForPlacement(use_context));
if(placement_state == null) { if(placement_state == null) {
Auxiliaries.logDebug("Placer spit: No valid placement state for item " + item.getRegistryName().toString()); Auxiliaries.logDebug("Placer spit: No valid placement state for item " + item.getRegistryName().toString());
return spit_out(facing); return spit_out(facing);
} else if((use_context!=null) && (item instanceof BlockItem)) { } else if((use_context!=null) && (item instanceof BlockItem)) {
if(((BlockItem)item).tryPlace(use_context) != ActionResultType.FAIL) { if(((BlockItem)item).place(use_context) != ActionResultType.FAIL) {
SoundType stype = block.getSoundType(placement_state, world, pos, null); SoundType stype = block.getSoundType(placement_state, level, worldPosition, null);
if(stype != null) world.playSound(null, placement_pos, stype.getPlaceSound(), SoundCategory.BLOCKS, stype.getVolume()*0.6f, stype.getPitch()); if(stype != null) level.playSound(null, placement_pos, stype.getPlaceSound(), SoundCategory.BLOCKS, stype.getVolume()*0.6f, stype.getPitch());
} else if(block instanceof IPlantable) { } else if(block instanceof IPlantable) {
if(world.setBlockState(placement_pos, placement_state, 1|2|8)) { if(level.setBlock(placement_pos, placement_state, 1|2|8)) {
SoundType stype = block.getSoundType(placement_state, world, pos, null); SoundType stype = block.getSoundType(placement_state, level, worldPosition, null);
if(stype != null) world.playSound(null, placement_pos, stype.getPlaceSound(), SoundCategory.BLOCKS, stype.getVolume()*0.6f, stype.getPitch()); if(stype != null) level.playSound(null, placement_pos, stype.getPlaceSound(), SoundCategory.BLOCKS, stype.getVolume()*0.6f, stype.getPitch());
} }
} else { } else {
Auxiliaries.logDebug("Placer spit: try-place and planting failed for item " + item.getRegistryName().toString()); Auxiliaries.logDebug("Placer spit: try-place and planting failed for item " + item.getRegistryName().toString());
return spit_out(facing); return spit_out(facing);
} }
} else { } else {
if(world.setBlockState(placement_pos, placement_state, 1|2|8)) { if(level.setBlock(placement_pos, placement_state, 1|2|8)) {
SoundType stype = block.getSoundType(placement_state, world, pos, null); SoundType stype = block.getSoundType(placement_state, level, worldPosition, null);
if(stype != null) world.playSound(null, placement_pos, stype.getPlaceSound(), SoundCategory.BLOCKS, stype.getVolume()*0.6f, stype.getPitch()); if(stype != null) level.playSound(null, placement_pos, stype.getPlaceSound(), SoundCategory.BLOCKS, stype.getVolume()*0.6f, stype.getPitch());
} }
} }
current_stack.shrink(1); current_stack.shrink(1);
@ -579,7 +579,7 @@ public class EdPlacer
// A hard crash should not be fired here, instead spit out the item to indicated that this // A hard crash should not be fired here, instead spit out the item to indicated that this
// block is not compatible. // block is not compatible.
ModEngineersDecor.logger().error("Exception while trying to place " + ((block==null)?(""):(""+block)) + ", spitting out. Exception is: " + e); ModEngineersDecor.logger().error("Exception while trying to place " + ((block==null)?(""):(""+block)) + ", spitting out. Exception is: " + e);
world.removeBlock(placement_pos, false); level.removeBlock(placement_pos, false);
return spit_out(facing, true); return spit_out(facing, true);
} }
} }
@ -597,27 +597,27 @@ public class EdPlacer
public void tick() public void tick()
{ {
// Tick cycle pre-conditions // Tick cycle pre-conditions
if(world.isRemote) return; if(level.isClientSide) return;
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
// Cycle init // Cycle init
final BlockState state = world.getBlockState(pos); final BlockState state = level.getBlockState(worldPosition);
if(!(state.getBlock() instanceof PlacerBlock)) { block_power_signal_= false; return; } if(!(state.getBlock() instanceof PlacerBlock)) { block_power_signal_= false; return; }
final boolean updated = block_power_updated_; final boolean updated = block_power_updated_;
final boolean rssignal = ((logic_ & LOGIC_IGNORE_EXT)!=0) || ((logic_ & LOGIC_INVERTED)!=0)==(!block_power_signal_); final boolean rssignal = ((logic_ & LOGIC_IGNORE_EXT)!=0) || ((logic_ & LOGIC_INVERTED)!=0)==(!block_power_signal_);
final boolean trigger = ((logic_ & LOGIC_IGNORE_EXT)!=0) || (rssignal && ((updated) || ((logic_ & LOGIC_CONTINUOUS)!=0))); final boolean trigger = ((logic_ & LOGIC_IGNORE_EXT)!=0) || (rssignal && ((updated) || ((logic_ & LOGIC_CONTINUOUS)!=0)));
final Direction placer_facing = state.get(PlacerBlock.FACING); final Direction placer_facing = state.getValue(PlacerBlock.FACING);
boolean dirty = updated; boolean dirty = updated;
// Trigger edge detection for next cycle // Trigger edge detection for next cycle
{ {
boolean tr = world.isBlockPowered(pos); boolean tr = level.hasNeighborSignal(worldPosition);
block_power_updated_ = (block_power_signal_ != tr); block_power_updated_ = (block_power_signal_ != tr);
block_power_signal_ = tr; block_power_signal_ = tr;
if(block_power_updated_) dirty = true; if(block_power_updated_) dirty = true;
} }
// Placing // Placing
if(trigger && try_place(placer_facing, rssignal && updated)) dirty = true; if(trigger && try_place(placer_facing, rssignal && updated)) dirty = true;
if(dirty) markDirty(); if(dirty) setChanged();
if(trigger && (tick_timer_ > TICK_INTERVAL)) tick_timer_ = TICK_INTERVAL; if(trigger && (tick_timer_ > TICK_INTERVAL)) tick_timer_ = TICK_INTERVAL;
} }
} }
@ -640,7 +640,7 @@ public class EdPlacer
public final int field(int index) { return fields_.get(index); } public final int field(int index) { return fields_.get(index); }
public PlacerContainer(int cid, PlayerInventory player_inventory) public PlacerContainer(int cid, PlayerInventory player_inventory)
{ this(cid, player_inventory, new Inventory(PlacerTileEntity.NUM_OF_SLOTS), IWorldPosCallable.DUMMY, new IntArray(PlacerTileEntity.NUM_OF_FIELDS)); } { this(cid, player_inventory, new Inventory(PlacerTileEntity.NUM_OF_SLOTS), IWorldPosCallable.NULL, new IntArray(PlacerTileEntity.NUM_OF_FIELDS)); }
private PlacerContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields) private PlacerContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields)
{ {
@ -668,34 +668,34 @@ public class EdPlacer
addSlot(new Slot(player_inventory, x+y*9+9, 9+x*18, 71+y*18)); // player slots: 9..35 addSlot(new Slot(player_inventory, x+y*9+9, 9+x*18, 71+y*18)); // player slots: 9..35
} }
} }
this.trackIntArray(fields_); // === Add reference holders this.addDataSlots(fields_); // === Add reference holders
} }
@Override @Override
public boolean canInteractWith(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return inventory_.isUsableByPlayer(player); } { return inventory_.stillValid(player); }
@Override @Override
public ItemStack transferStackInSlot(PlayerEntity player, int index) public ItemStack quickMoveStack(PlayerEntity player, int index)
{ {
Slot slot = getSlot(index); Slot slot = getSlot(index);
if((slot==null) || (!slot.getHasStack())) return ItemStack.EMPTY; if((slot==null) || (!slot.hasItem())) return ItemStack.EMPTY;
ItemStack slot_stack = slot.getStack(); ItemStack slot_stack = slot.getItem();
ItemStack transferred = slot_stack.copy(); ItemStack transferred = slot_stack.copy();
if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) { if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) {
// Device slots // Device slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, false)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) {
// Player slot // Player slot
if(!mergeItemStack(slot_stack, 0, PlacerTileEntity.NUM_OF_SLOTS, false)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, 0, PlacerTileEntity.NUM_OF_SLOTS, false)) return ItemStack.EMPTY;
} else { } else {
// invalid slot // invalid slot
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
if(slot_stack.isEmpty()) { if(slot_stack.isEmpty()) {
slot.putStack(ItemStack.EMPTY); slot.set(ItemStack.EMPTY);
} else { } else {
slot.onSlotChanged(); slot.setChanged();
} }
if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY; if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY;
slot.onTake(player, slot_stack); slot.onTake(player, slot_stack);
@ -706,21 +706,21 @@ public class EdPlacer
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(CompoundNBT nbt) public void onGuiAction(CompoundNBT nbt)
{ Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); } { Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt); }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(String key, int value) public void onGuiAction(String key, int value)
{ {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt(key, value); nbt.putInt(key, value);
Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt);
} }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void onGuiAction(String message, CompoundNBT nbt) public void onGuiAction(String message, CompoundNBT nbt)
{ {
nbt.putString("action", message); nbt.putString("action", message);
Networking.PacketContainerSyncClientToServer.sendToServer(windowId, nbt); Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt);
} }
@Override @Override
@ -736,23 +736,23 @@ public class EdPlacer
final int slotId = nbt.contains("slot") ? nbt.getInt("slot") : -1; final int slotId = nbt.contains("slot") ? nbt.getInt("slot") : -1;
switch(nbt.getString("action")) { switch(nbt.getString("action")) {
case QUICK_MOVE_ALL: { case QUICK_MOVE_ALL: {
if((slotId >= 0) && (slotId < PLAYER_INV_START_SLOTNO) && (getSlot(slotId).getHasStack())) { if((slotId >= 0) && (slotId < PLAYER_INV_START_SLOTNO) && (getSlot(slotId).hasItem())) {
changed = block_storage_range_.move(getSlot(slotId).getSlotIndex(), player_inventory_range_, true, false, true, true); changed = block_storage_range_.move(getSlot(slotId).getSlotIndex(), player_inventory_range_, true, false, true, true);
} else if((slotId >= PLAYER_INV_START_SLOTNO) && (slotId < PLAYER_INV_START_SLOTNO+36) && (getSlot(slotId).getHasStack())) { } else if((slotId >= PLAYER_INV_START_SLOTNO) && (slotId < PLAYER_INV_START_SLOTNO+36) && (getSlot(slotId).hasItem())) {
changed = player_inventory_range_.move(getSlot(slotId).getSlotIndex(), block_storage_range_, true, false, false, true); changed = player_inventory_range_.move(getSlot(slotId).getSlotIndex(), block_storage_range_, true, false, false, true);
} }
} break; } break;
} }
if(changed) { if(changed) {
inventory_.markDirty(); inventory_.setChanged();
player.inventory.markDirty(); player.inventory.setChanged();
detectAndSendChanges(); broadcastChanges();
} }
} else { } else {
PlacerTileEntity te = (PlacerTileEntity)inventory_; PlacerTileEntity te = (PlacerTileEntity)inventory_;
if(nbt.contains("logic")) te.logic_ = nbt.getInt("logic"); if(nbt.contains("logic")) te.logic_ = nbt.getInt("logic");
if(nbt.contains("manual_trigger") && (nbt.getInt("manual_trigger")!=0)) { te.block_power_signal_=true; te.block_power_updated_=true; te.tick_timer_=1; } if(nbt.contains("manual_trigger") && (nbt.getInt("manual_trigger")!=0)) { te.block_power_signal_=true; te.block_power_updated_=true; te.tick_timer_=1; }
te.markDirty(); te.setChanged();
} }
} }
@ -776,7 +776,7 @@ public class EdPlacer
{ {
super.init(); super.init();
{ {
final String prefix = ModContent.FACTORY_PLACER.getTranslationKey() + ".tooltips."; final String prefix = ModContent.FACTORY_PLACER.getDescriptionId() + ".tooltips.";
final int x0 = getGuiLeft(), y0 = getGuiTop(); final int x0 = getGuiLeft(), y0 = getGuiTop();
tooltip_.init( tooltip_.init(
new TipRange(x0+133, y0+49, 9, 9, new TranslationTextComponent(prefix + "rssignal")), new TipRange(x0+133, y0+49, 9, 9, new TranslationTextComponent(prefix + "rssignal")),
@ -791,24 +791,24 @@ public class EdPlacer
{ {
renderBackground(mx); renderBackground(mx);
super.render(mx, mouseX, mouseY, partialTicks); super.render(mx, mouseX, mouseY, partialTicks);
if(!tooltip_.render(mx, this, mouseX, mouseY)) renderHoveredTooltip(mx, mouseX, mouseY); if(!tooltip_.render(mx, this, mouseX, mouseY)) renderTooltip(mx, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerForegroundLayer(MatrixStack mx, int x, int y) protected void renderLabels(MatrixStack mx, int x, int y)
{} {}
@Override @Override
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) public boolean mouseClicked(double mouseX, double mouseY, int mouseButton)
{ {
tooltip_.resetTimer(); tooltip_.resetTimer();
PlacerContainer container = (PlacerContainer)getContainer(); PlacerContainer container = (PlacerContainer)getMenu();
int mx = (int)(mouseX - getGuiLeft() + .5), my = (int)(mouseY - getGuiTop() + .5); int mx = (int)(mouseX - getGuiLeft() + .5), my = (int)(mouseY - getGuiTop() + .5);
if((!isPointInRegion(126, 1, 49, 60, mouseX, mouseY))) { if((!isHovering(126, 1, 49, 60, mouseX, mouseY))) {
return super.mouseClicked(mouseX, mouseY, mouseButton); return super.mouseClicked(mouseX, mouseY, mouseButton);
} else if(isPointInRegion(133, 49, 9, 9, mouseX, mouseY)) { } else if(isHovering(133, 49, 9, 9, mouseX, mouseY)) {
container.onGuiAction("manual_trigger", 1); container.onGuiAction("manual_trigger", 1);
} else if(isPointInRegion(145, 49, 9, 9, mouseX, mouseY)) { } else if(isHovering(145, 49, 9, 9, mouseX, mouseY)) {
final int mask = (PlacerTileEntity.LOGIC_INVERTED|PlacerTileEntity.LOGIC_IGNORE_EXT|PlacerTileEntity.LOGIC_NOT_INVERTED); final int mask = (PlacerTileEntity.LOGIC_INVERTED|PlacerTileEntity.LOGIC_IGNORE_EXT|PlacerTileEntity.LOGIC_NOT_INVERTED);
int logic = (container.field(0) & mask); int logic = (container.field(0) & mask);
switch(logic) { switch(logic) {
@ -818,35 +818,35 @@ public class EdPlacer
default: logic = PlacerTileEntity.LOGIC_IGNORE_EXT; default: logic = PlacerTileEntity.LOGIC_IGNORE_EXT;
} }
container.onGuiAction("logic", (container.field(0) & (~mask)) | logic); container.onGuiAction("logic", (container.field(0) & (~mask)) | logic);
} else if(isPointInRegion(159, 49, 7, 9, mouseX, mouseY)) { } else if(isHovering(159, 49, 7, 9, mouseX, mouseY)) {
container.onGuiAction("logic", container.field(0) ^ PlacerTileEntity.LOGIC_CONTINUOUS); container.onGuiAction("logic", container.field(0) ^ PlacerTileEntity.LOGIC_CONTINUOUS);
} }
return true; return true;
} }
@Override @Override
protected void handleMouseClick(Slot slot, int slotId, int button, ClickType type) protected void slotClicked(Slot slot, int slotId, int button, ClickType type)
{ {
tooltip_.resetTimer(); tooltip_.resetTimer();
if((type == ClickType.QUICK_MOVE) && (slot!=null) && slot.getHasStack() && Auxiliaries.isShiftDown() && Auxiliaries.isCtrlDown()) { if((type == ClickType.QUICK_MOVE) && (slot!=null) && slot.hasItem() && Auxiliaries.isShiftDown() && Auxiliaries.isCtrlDown()) {
CompoundNBT nbt = new CompoundNBT(); CompoundNBT nbt = new CompoundNBT();
nbt.putInt("slot", slotId); nbt.putInt("slot", slotId);
container.onGuiAction(PlacerContainer.QUICK_MOVE_ALL, nbt); menu.onGuiAction(PlacerContainer.QUICK_MOVE_ALL, nbt);
} else { } else {
super.handleMouseClick(slot, slotId, button, type); super.slotClicked(slot, slotId, button, type);
} }
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void drawGuiContainerBackgroundLayer(MatrixStack mx, float partialTicks, int mouseX, int mouseY) protected void renderBg(MatrixStack mx, float partialTicks, int mouseX, int mouseY)
{ {
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
this.getMinecraft().getTextureManager().bindTexture(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/factory_placer_gui.png")); this.getMinecraft().getTextureManager().bind(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/factory_placer_gui.png"));
final int x0=getGuiLeft(), y0=getGuiTop(), w=getXSize(), h=getYSize(); final int x0=getGuiLeft(), y0=getGuiTop(), w=getXSize(), h=getYSize();
blit(mx, x0, y0, 0, 0, w, h); blit(mx, x0, y0, 0, 0, w, h);
PlacerContainer container = (PlacerContainer)getContainer(); PlacerContainer container = (PlacerContainer)getMenu();
// active slot // active slot
{ {
int slot_index = container.field(2); int slot_index = container.field(2);

View file

@ -8,7 +8,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.Block; import net.minecraft.block.AbstractBlock;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
@ -29,9 +29,10 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
public class EdRailingBlock extends DecorBlock.HorizontalFourWayWaterLoggable implements IDecorBlock public class EdRailingBlock extends DecorBlock.HorizontalFourWayWaterLoggable implements IDecorBlock
{ {
public EdRailingBlock(long config, Block.Properties properties, final AxisAlignedBB base_aabb, final AxisAlignedBB railing_aabb) public EdRailingBlock(long config, AbstractBlock.Properties properties, final AxisAlignedBB base_aabb, final AxisAlignedBB railing_aabb)
{ super(config, properties, base_aabb, railing_aabb, 0); } { super(config, properties, base_aabb, railing_aabb, 0); }
@Override @Override
@ -40,40 +41,40 @@ public class EdRailingBlock extends DecorBlock.HorizontalFourWayWaterLoggable im
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean isReplaceable(BlockState state, BlockItemUseContext useContext) public boolean canBeReplaced(BlockState state, BlockItemUseContext useContext)
{ return (useContext.getItem().getItem() == asItem()) ? true : super.isReplaceable(state, useContext); } { return (useContext.getItemInHand().getItem() == asItem()) ? true : super.canBeReplaced(state, useContext); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
if(context.getFace() != Direction.UP) return null; if(context.getClickedFace() != Direction.UP) return null;
BlockState state = context.getWorld().getBlockState(context.getPos()); BlockState state = context.getLevel().getBlockState(context.getClickedPos());
if(state.getBlock() != this) state = super.getStateForPlacement(context); if(state.getBlock() != this) state = super.getStateForPlacement(context);
final Vector3d rhv = context.getHitVec().subtract(Vector3d.copyCentered(context.getPos())); final Vector3d rhv = context.getClickLocation().subtract(Vector3d.atCenterOf(context.getClickedPos()));
BooleanProperty side = getDirectionProperty(Direction.getFacingFromVector(rhv.x, 0, rhv.z)); BooleanProperty side = getDirectionProperty(Direction.getNearest(rhv.x, 0, rhv.z));
return state.with(side, true); return state.setValue(side, true);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
if(player.getHeldItem(hand).getItem() != asItem()) return ActionResultType.PASS; if(player.getItemInHand(hand).getItem() != asItem()) return ActionResultType.PASS;
Direction face = hit.getFace(); Direction face = hit.getDirection();
if(!face.getAxis().isHorizontal()) return ActionResultType.func_233537_a_(world.isRemote()); if(!face.getAxis().isHorizontal()) return ActionResultType.sidedSuccess(world.isClientSide());
final Vector3d rhv = hit.getHitVec().subtract(Vector3d.copyCentered(hit.getPos())); final Vector3d rhv = hit.getLocation().subtract(Vector3d.atCenterOf(hit.getBlockPos()));
if(rhv.mul(Vector3d.copy(face.getDirectionVec())).scale(2).lengthSquared() < 0.99) face = face.getOpposite(); // click on railing, not the outer side. if(rhv.multiply(Vector3d.atLowerCornerOf(face.getNormal())).scale(2).lengthSqr() < 0.99) face = face.getOpposite(); // click on railing, not the outer side.
BooleanProperty railing = getDirectionProperty(face); BooleanProperty railing = getDirectionProperty(face);
boolean add = (!state.get(railing)); boolean add = (!state.getValue(railing));
state = state.with(railing, add); state = state.setValue(railing, add);
if((!state.get(NORTH)) && (!state.get(EAST)) && (!state.get(SOUTH)) && (!state.get(WEST))) { if((!state.getValue(NORTH)) && (!state.getValue(EAST)) && (!state.getValue(SOUTH)) && (!state.getValue(WEST))) {
state = (world.getFluidState(pos).getFluid() == Fluids.WATER) ? Blocks.WATER.getDefaultState() : (Blocks.AIR.getDefaultState()); state = (world.getFluidState(pos).getType() == Fluids.WATER) ? Blocks.WATER.defaultBlockState() : (Blocks.AIR.defaultBlockState());
EdCatwalkBlock.place_consume(state, world, pos, player, hand, add ? 1 : -1); EdCatwalkBlock.place_consume(state, world, pos, player, hand, add ? 1 : -1);
} else { } else {
EdCatwalkBlock.place_consume(state, world, pos, player, hand, add ? 1 : -1); EdCatwalkBlock.place_consume(state, world, pos, player, hand, add ? 1 : -1);
} }
return ActionResultType.func_233537_a_(world.isRemote()); return ActionResultType.sidedSuccess(world.isClientSide());
} }
// -- IDecorBlock // -- IDecorBlock
@ -85,9 +86,9 @@ public class EdRailingBlock extends DecorBlock.HorizontalFourWayWaterLoggable im
@Override @Override
public List<ItemStack> dropList(BlockState state, World world, @Nullable TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, @Nullable TileEntity te, boolean explosion)
{ {
if(world.isRemote()) return Collections.singletonList(ItemStack.EMPTY); if(world.isClientSide()) return Collections.singletonList(ItemStack.EMPTY);
List<ItemStack> drops = new ArrayList<>(); List<ItemStack> drops = new ArrayList<>();
int n = (state.get(NORTH)?1:0)+(state.get(EAST)?1:0)+(state.get(SOUTH)?1:0)+(state.get(WEST)?1:0); int n = (state.getValue(NORTH)?1:0)+(state.getValue(EAST)?1:0)+(state.getValue(SOUTH)?1:0)+(state.getValue(WEST)?1:0);
drops.add(new ItemStack(state.getBlock().asItem(), Math.max(n, 1))); drops.add(new ItemStack(state.getBlock().asItem(), Math.max(n, 1)));
return drops; return drops;
} }

View file

@ -41,88 +41,88 @@ public class EdRoofBlock extends StandardBlocks.HorizontalWaterLoggable implemen
public static final EnumProperty<Half> HALF = BlockStateProperties.HALF; public static final EnumProperty<Half> HALF = BlockStateProperties.HALF;
private final VoxelShape[][][] shape_cache_; private final VoxelShape[][][] shape_cache_;
public EdRoofBlock(long config, Block.Properties properties) public EdRoofBlock(long config, AbstractBlock.Properties properties)
{ this(config, properties.variableOpacity(), VoxelShapes.empty(), VoxelShapes.empty()); } { this(config, properties.dynamicShape(), VoxelShapes.empty(), VoxelShapes.empty()); }
public EdRoofBlock(long config, Block.Properties properties, VoxelShape add, VoxelShape cut) public EdRoofBlock(long config, AbstractBlock.Properties properties, VoxelShape add, VoxelShape cut)
{ {
super(config, properties, Auxiliaries.getPixeledAABB(0, 0,0,16, 8, 16)); super(config, properties, Auxiliaries.getPixeledAABB(0, 0,0,16, 8, 16));
setDefaultState(super.getDefaultState().with(HORIZONTAL_FACING, Direction.NORTH).with(SHAPE, StairsShape.STRAIGHT)); registerDefaultState(super.defaultBlockState().setValue(HORIZONTAL_FACING, Direction.NORTH).setValue(SHAPE, StairsShape.STRAIGHT));
shape_cache_ = makeShapes(add, cut); shape_cache_ = makeShapes(add, cut);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean isTransparent(BlockState state) public boolean useShapeForLightOcclusion(BlockState state)
{ return false; } { return false; }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public float getAmbientOcclusionLightValue(BlockState state, IBlockReader world, BlockPos pos) public float getShadeBrightness(BlockState state, IBlockReader world, BlockPos pos)
{ return 0.98f; } { return 0.98f; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getOpacity(BlockState state, IBlockReader world, BlockPos pos) public int getLightBlock(BlockState state, IBlockReader world, BlockPos pos)
{ return 1; } { return 1; }
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext context) public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext context)
{ return shape_cache_[state.get(HALF).ordinal()][state.get(HORIZONTAL_FACING).getIndex()][state.get(SHAPE).ordinal()]; } { return shape_cache_[state.getValue(HALF).ordinal()][state.getValue(HORIZONTAL_FACING).get3DDataValue()][state.getValue(SHAPE).ordinal()]; }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(SHAPE, HALF); } { super.createBlockStateDefinition(builder); builder.add(SHAPE, HALF); }
@Override @Override
public FluidState getFluidState(BlockState state) public FluidState getFluidState(BlockState state)
{ return state.get(WATERLOGGED) ? Fluids.WATER.getStillFluidState(false) : super.getFluidState(state); } { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); }
@Override @Override
public boolean allowsMovement(BlockState state, IBlockReader world, BlockPos pos, PathType type) public boolean isPathfindable(BlockState state, IBlockReader world, BlockPos pos, PathType type)
{ return false; } { return false; }
@Override @Override
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
BlockPos pos = context.getPos(); BlockPos pos = context.getClickedPos();
Direction face = context.getFace(); Direction face = context.getClickedFace();
BlockState state = getDefaultState() BlockState state = defaultBlockState()
.with(HORIZONTAL_FACING, context.getPlacementHorizontalFacing()) .setValue(HORIZONTAL_FACING, context.getHorizontalDirection())
.with(HALF, (face == Direction.DOWN) ? Half.TOP : Half.BOTTOM) .setValue(HALF, (face == Direction.DOWN) ? Half.TOP : Half.BOTTOM)
.with(WATERLOGGED, context.getWorld().getFluidState(pos).getFluid()==Fluids.WATER); .setValue(WATERLOGGED, context.getLevel().getFluidState(pos).getType()==Fluids.WATER);
return state.with(SHAPE, getStairsShapeProperty(state, context.getWorld(), pos)); return state.setValue(SHAPE, getStairsShapeProperty(state, context.getLevel(), pos));
} }
@Override @Override
public BlockState updatePostPlacement(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos) public BlockState updateShape(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos)
{ {
if(state.get(WATERLOGGED)) world.getPendingFluidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickRate(world)); if(state.getValue(WATERLOGGED)) world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world));
return (facing.getAxis().isHorizontal()) ? (state.with(SHAPE, getStairsShapeProperty(state, world, pos))) : (super.updatePostPlacement(state, facing, facingState, world, pos, facingPos)); return (facing.getAxis().isHorizontal()) ? (state.setValue(SHAPE, getStairsShapeProperty(state, world, pos))) : (super.updateShape(state, facing, facingState, world, pos, facingPos));
} }
@Override @Override
public BlockState rotate(BlockState state, Rotation rot) public BlockState rotate(BlockState state, Rotation rot)
{ return state.with(HORIZONTAL_FACING, rot.rotate(state.get(HORIZONTAL_FACING))); } { return state.setValue(HORIZONTAL_FACING, rot.rotate(state.getValue(HORIZONTAL_FACING))); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState mirror(BlockState state, Mirror where) public BlockState mirror(BlockState state, Mirror where)
{ {
if((where==Mirror.LEFT_RIGHT) && (state.get(HORIZONTAL_FACING).getAxis()==Direction.Axis.Z)) { if((where==Mirror.LEFT_RIGHT) && (state.getValue(HORIZONTAL_FACING).getAxis()==Direction.Axis.Z)) {
switch(state.get(SHAPE)) { switch(state.getValue(SHAPE)) {
case INNER_LEFT: return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.INNER_RIGHT); case INNER_LEFT: return state.rotate(Rotation.CLOCKWISE_180).setValue(SHAPE, StairsShape.INNER_RIGHT);
case INNER_RIGHT: return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.INNER_LEFT); case INNER_RIGHT: return state.rotate(Rotation.CLOCKWISE_180).setValue(SHAPE, StairsShape.INNER_LEFT);
case OUTER_LEFT: return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.OUTER_RIGHT); case OUTER_LEFT: return state.rotate(Rotation.CLOCKWISE_180).setValue(SHAPE, StairsShape.OUTER_RIGHT);
case OUTER_RIGHT: return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.OUTER_LEFT); case OUTER_RIGHT: return state.rotate(Rotation.CLOCKWISE_180).setValue(SHAPE, StairsShape.OUTER_LEFT);
default: return state.rotate(Rotation.CLOCKWISE_180); default: return state.rotate(Rotation.CLOCKWISE_180);
} }
} else if((where==Mirror.FRONT_BACK) && (state.get(HORIZONTAL_FACING).getAxis() == Direction.Axis.X)) { } else if((where==Mirror.FRONT_BACK) && (state.getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.X)) {
switch(state.get(SHAPE)) { switch(state.getValue(SHAPE)) {
case INNER_LEFT: return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.INNER_LEFT); case INNER_LEFT: return state.rotate(Rotation.CLOCKWISE_180).setValue(SHAPE, StairsShape.INNER_LEFT);
case INNER_RIGHT: return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.INNER_RIGHT); case INNER_RIGHT: return state.rotate(Rotation.CLOCKWISE_180).setValue(SHAPE, StairsShape.INNER_RIGHT);
case OUTER_LEFT: return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.OUTER_RIGHT); case OUTER_LEFT: return state.rotate(Rotation.CLOCKWISE_180).setValue(SHAPE, StairsShape.OUTER_RIGHT);
case OUTER_RIGHT: return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.OUTER_LEFT); case OUTER_RIGHT: return state.rotate(Rotation.CLOCKWISE_180).setValue(SHAPE, StairsShape.OUTER_LEFT);
case STRAIGHT: return state.rotate(Rotation.CLOCKWISE_180); case STRAIGHT: return state.rotate(Rotation.CLOCKWISE_180);
} }
} }
@ -134,8 +134,8 @@ public class EdRoofBlock extends StandardBlocks.HorizontalWaterLoggable implemen
private static boolean isOtherRoofState(BlockState state, IBlockReader world, BlockPos pos, Direction facing) private static boolean isOtherRoofState(BlockState state, IBlockReader world, BlockPos pos, Direction facing)
{ {
BlockState st = world.getBlockState(pos.offset(facing)); BlockState st = world.getBlockState(pos.relative(facing));
return (!isRoofBlock(st)) || (st.get(HORIZONTAL_FACING) != state.get(HORIZONTAL_FACING)); return (!isRoofBlock(st)) || (st.getValue(HORIZONTAL_FACING) != state.getValue(HORIZONTAL_FACING));
} }
private static VoxelShape[][][] makeShapes(VoxelShape add, VoxelShape cut) private static VoxelShape[][][] makeShapes(VoxelShape add, VoxelShape cut)
@ -148,8 +148,8 @@ public class EdRoofBlock extends StandardBlocks.HorizontalWaterLoggable implemen
try { try {
// Only in case something changes and this fails, log but do not prevent the game from starting. // Only in case something changes and this fails, log but do not prevent the game from starting.
// Roof shapes are not the most important thing in the world. // Roof shapes are not the most important thing in the world.
if(!add.isEmpty()) shape = VoxelShapes.combine(shape, add, IBooleanFunction.OR); if(!add.isEmpty()) shape = VoxelShapes.joinUnoptimized(shape, add, IBooleanFunction.OR);
if(!cut.isEmpty()) shape = VoxelShapes.combine(shape, cut, IBooleanFunction.ONLY_FIRST); if(!cut.isEmpty()) shape = VoxelShapes.joinUnoptimized(shape, cut, IBooleanFunction.ONLY_FIRST);
} catch(Throwable ex) { } catch(Throwable ex) {
Auxiliaries.logError("Failed to cut shape using Boolean function. This is bug."); Auxiliaries.logError("Failed to cut shape using Boolean function. This is bug.");
} }
@ -179,9 +179,9 @@ public class EdRoofBlock extends StandardBlocks.HorizontalWaterLoggable implemen
straight = Auxiliaries.getMirroredAABB(straight, Axis.Y); straight = Auxiliaries.getMirroredAABB(straight, Axis.Y);
pyramid = Auxiliaries.getMirroredAABB(pyramid, Axis.Y); pyramid = Auxiliaries.getMirroredAABB(pyramid, Axis.Y);
} }
Direction direction = Direction.byIndex(direction_index); Direction direction = Direction.from3DDataValue(direction_index);
if((direction==Direction.UP) || (direction==Direction.DOWN)) return VoxelShapes.fullCube(); if((direction==Direction.UP) || (direction==Direction.DOWN)) return VoxelShapes.block();
direction_index = (direction.getHorizontalIndex()+1) & 0x03; // ref NORTH -> EAST for stairs compliancy. direction_index = (direction.get2DDataValue()+1) & 0x03; // ref NORTH -> EAST for stairs compliancy.
final StairsShape stairs = StairsShape.values()[stairs_shape_index]; final StairsShape stairs = StairsShape.values()[stairs_shape_index];
switch(stairs) { switch(stairs) {
case STRAIGHT: case STRAIGHT:
@ -201,28 +201,28 @@ public class EdRoofBlock extends StandardBlocks.HorizontalWaterLoggable implemen
Auxiliaries.getYRotatedAABB(straight, direction_index+1) Auxiliaries.getYRotatedAABB(straight, direction_index+1)
); );
default: default:
return VoxelShapes.fullCube(); return VoxelShapes.block();
} }
} }
private static StairsShape getStairsShapeProperty(BlockState state, IBlockReader world, BlockPos pos) private static StairsShape getStairsShapeProperty(BlockState state, IBlockReader world, BlockPos pos)
{ {
Direction direction = state.get(HORIZONTAL_FACING); Direction direction = state.getValue(HORIZONTAL_FACING);
{ {
BlockState ns = world.getBlockState(pos.offset(direction)); BlockState ns = world.getBlockState(pos.relative(direction));
if(isRoofBlock(ns) && (state.get(HALF) == ns.get(HALF))) { if(isRoofBlock(ns) && (state.getValue(HALF) == ns.getValue(HALF))) {
Direction nf = ns.get(HORIZONTAL_FACING); Direction nf = ns.getValue(HORIZONTAL_FACING);
if(nf.getAxis() != state.get(HORIZONTAL_FACING).getAxis() && isOtherRoofState(state, world, pos, nf.getOpposite())) { if(nf.getAxis() != state.getValue(HORIZONTAL_FACING).getAxis() && isOtherRoofState(state, world, pos, nf.getOpposite())) {
return (nf == direction.rotateYCCW()) ? StairsShape.OUTER_LEFT : StairsShape.OUTER_RIGHT; return (nf == direction.getCounterClockWise()) ? StairsShape.OUTER_LEFT : StairsShape.OUTER_RIGHT;
} }
} }
} }
{ {
BlockState ns = world.getBlockState(pos.offset(direction.getOpposite())); BlockState ns = world.getBlockState(pos.relative(direction.getOpposite()));
if(isRoofBlock(ns) && (state.get(HALF) == ns.get(HALF))) { if(isRoofBlock(ns) && (state.getValue(HALF) == ns.getValue(HALF))) {
Direction nf = ns.get(HORIZONTAL_FACING); Direction nf = ns.getValue(HORIZONTAL_FACING);
if(nf.getAxis() != state.get(HORIZONTAL_FACING).getAxis() && isOtherRoofState(state, world, pos, nf)) { if(nf.getAxis() != state.getValue(HORIZONTAL_FACING).getAxis() && isOtherRoofState(state, world, pos, nf)) {
return (nf == direction.rotateYCCW()) ? StairsShape.INNER_LEFT : StairsShape.INNER_RIGHT; return (nf == direction.getCounterClockWise()) ? StairsShape.INNER_LEFT : StairsShape.INNER_RIGHT;
} }
} }
} }

View file

@ -13,6 +13,6 @@ import net.minecraft.block.*;
public class EdSlabBlock extends VariantSlabBlock implements IDecorBlock public class EdSlabBlock extends VariantSlabBlock implements IDecorBlock
{ {
public EdSlabBlock(long config, Block.Properties builder) public EdSlabBlock(long config, AbstractBlock.Properties builder)
{ super(config, builder); } { super(config, builder); }
} }

View file

@ -10,10 +10,10 @@
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import wile.engineersdecor.libmc.blocks.SlabSliceBlock; import wile.engineersdecor.libmc.blocks.SlabSliceBlock;
import net.minecraft.block.*; import net.minecraft.block.AbstractBlock;
public class EdSlabSliceBlock extends SlabSliceBlock implements IDecorBlock public class EdSlabSliceBlock extends SlabSliceBlock implements IDecorBlock
{ {
public EdSlabSliceBlock(long config, Block.Properties builder) public EdSlabSliceBlock(long config, AbstractBlock.Properties builder)
{ super(config, builder); } { super(config, builder); }
} }

View file

@ -42,6 +42,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.minecraft.block.AbstractBlock;
public class EdSolarPanel public class EdSolarPanel
{ {
public static void on_config(int peak_power_per_tick) public static void on_config(int peak_power_per_tick)
@ -55,15 +57,15 @@ public class EdSolarPanel
{ {
public static final IntegerProperty EXPOSITION = IntegerProperty.create("exposition", 0, 4); public static final IntegerProperty EXPOSITION = IntegerProperty.create("exposition", 0, 4);
public SolarPanelBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABB) public SolarPanelBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABB)
{ {
super(config, builder, unrotatedAABB); super(config, builder, unrotatedAABB);
setDefaultState(super.getDefaultState().with(EXPOSITION, 1)); registerDefaultState(super.defaultBlockState().setValue(EXPOSITION, 1));
} }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(EXPOSITION); } { super.createBlockStateDefinition(builder); builder.add(EXPOSITION); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -76,10 +78,10 @@ public class EdSolarPanel
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(te instanceof SolarPanelTileEntity) ((SolarPanelTileEntity)te).state_message(player); if(te instanceof SolarPanelTileEntity) ((SolarPanelTileEntity)te).state_message(player);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@ -100,8 +102,8 @@ public class EdSolarPanel
public static final int ACCUMULATION_INTERVAL = 8; public static final int ACCUMULATION_INTERVAL = 8;
private static final Direction transfer_directions_[] = {Direction.DOWN, Direction.EAST, Direction.SOUTH, Direction.WEST, Direction.NORTH }; private static final Direction transfer_directions_[] = {Direction.DOWN, Direction.EAST, Direction.SOUTH, Direction.WEST, Direction.NORTH };
private static int peak_power_per_tick_ = DEFAULT_PEAK_POWER; private static int peak_power_per_tick_ = DEFAULT_PEAK_POWER;
private static int max_power_storage_ = 64000; private static final int max_power_storage_ = 64000;
private static int max_feed_power = 8192; private static final int max_feed_power = 8192;
private static int feeding_threshold = max_power_storage_/5; private static int feeding_threshold = max_power_storage_/5;
private static int balancing_threshold = max_power_storage_/10; private static int balancing_threshold = max_power_storage_/10;
private int tick_timer_ = 0; private int tick_timer_ = 0;
@ -183,33 +185,33 @@ public class EdSolarPanel
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt, false); } { super.load(state, nbt); readnbt(nbt, false); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt, false); return nbt; } { super.save(nbt); writenbt(nbt, false); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
energy_handler_.invalidate(); energy_handler_.invalidate();
} }
@Override @Override
public void tick() public void tick()
{ {
if((world.isRemote) || (--tick_timer_ > 0)) return; if((level.isClientSide) || (--tick_timer_ > 0)) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
BlockState state = world.getBlockState(pos); BlockState state = level.getBlockState(worldPosition);
if(!(state.getBlock() instanceof SolarPanelBlock)) return; if(!(state.getBlock() instanceof SolarPanelBlock)) return;
current_feedin_ = 0; current_feedin_ = 0;
final List<SolarPanelTileEntity> adjacent_panels = new ArrayList<>(); final List<SolarPanelTileEntity> adjacent_panels = new ArrayList<>();
if(output_enabled_) { if(output_enabled_) {
for(int i=0; (i<transfer_directions_.length) && (accumulated_power_>0); ++i) { for(int i=0; (i<transfer_directions_.length) && (accumulated_power_>0); ++i) {
final Direction f = transfer_directions_[i]; final Direction f = transfer_directions_[i];
TileEntity te = world.getTileEntity(pos.offset(f)); TileEntity te = level.getBlockEntity(worldPosition.relative(f));
if(te==null) continue; if(te==null) continue;
IEnergyStorage es = te.getCapability(CapabilityEnergy.ENERGY, f.getOpposite()).orElse(null); IEnergyStorage es = te.getCapability(CapabilityEnergy.ENERGY, f.getOpposite()).orElse(null);
if(es==null) continue; if(es==null) continue;
@ -233,17 +235,17 @@ public class EdSolarPanel
if(accumulated_power_ < balancing_threshold) break; if(accumulated_power_ < balancing_threshold) break;
} }
} }
if(!world.canBlockSeeSky(pos)) { if(!level.canSeeSkyFromBelowWater(worldPosition)) {
tick_timer_ = TICK_INTERVAL * 10; tick_timer_ = TICK_INTERVAL * 10;
current_production_ = 0; current_production_ = 0;
if((accumulated_power_ > 0)) output_enabled_ = true; if((accumulated_power_ > 0)) output_enabled_ = true;
if(state.get((SolarPanelBlock.EXPOSITION))!=2) world.setBlockState(pos, state.with(SolarPanelBlock.EXPOSITION, 2)); if(state.getValue((SolarPanelBlock.EXPOSITION))!=2) level.setBlockAndUpdate(worldPosition, state.setValue(SolarPanelBlock.EXPOSITION, 2));
return; return;
} }
if(accumulated_power_ <= 0) output_enabled_ = false; if(accumulated_power_ <= 0) output_enabled_ = false;
if(--recalc_timer_ > 0) return; if(--recalc_timer_ > 0) return;
recalc_timer_ = ACCUMULATION_INTERVAL + ((int)(Math.random()+.5)); recalc_timer_ = ACCUMULATION_INTERVAL + ((int)(Math.random()+.5));
int theta = ((((int)(world.getCelestialAngleRadians(1f) * (180.0/Math.PI)))+90) % 360); int theta = ((((int)(level.getSunAngle(1f) * (180.0/Math.PI)))+90) % 360);
int e = 2; int e = 2;
if(theta > 340) e = 2; if(theta > 340) e = 2;
else if(theta < 45) e = 0; else if(theta < 45) e = 0;
@ -251,10 +253,10 @@ public class EdSolarPanel
else if(theta < 100) e = 2; else if(theta < 100) e = 2;
else if(theta < 135) e = 3; else if(theta < 135) e = 3;
else if(theta < 190) e = 4; else if(theta < 190) e = 4;
BlockState nstate = state.with(SolarPanelBlock.EXPOSITION, e); BlockState nstate = state.setValue(SolarPanelBlock.EXPOSITION, e);
if(nstate != state) world.setBlockState(pos, nstate, 1|2); if(nstate != state) level.setBlock(worldPosition, nstate, 1|2);
final double eff = (1.0-((world.getRainStrength(1f)*0.6)+(world.getThunderStrength(1f)*0.3))); final double eff = (1.0-((level.getRainLevel(1f)*0.6)+(level.getThunderLevel(1f)*0.3)));
final double ll = ((double)(world.getLightManager().getLightEngine(LightType.SKY).getLightFor(getPos())))/15; final double ll = ((double)(level.getLightEngine().getLayerListener(LightType.SKY).getLightValue(getBlockPos())))/15;
final double rf = Math.sin((Math.PI/2) * Math.sqrt(((double)(((theta<0)||(theta>180))?(0):((theta>90)?(180-theta):(theta))))/90)); final double rf = Math.sin((Math.PI/2) * Math.sqrt(((double)(((theta<0)||(theta>180))?(0):((theta>90)?(180-theta):(theta))))/90));
current_production_ = (int)(Math.min(rf*rf*eff*ll, 1) * peak_power_per_tick_); current_production_ = (int)(Math.min(rf*rf*eff*ll, 1) * peak_power_per_tick_);
accumulated_power_ = Math.min(accumulated_power_ + (current_production_*(TICK_INTERVAL*ACCUMULATION_INTERVAL)), max_power_storage_); accumulated_power_ = Math.min(accumulated_power_ + (current_production_*(TICK_INTERVAL*ACCUMULATION_INTERVAL)), max_power_storage_);

View file

@ -14,9 +14,9 @@ import net.minecraft.block.BlockState;
public class EdStairsBlock extends StandardStairsBlock implements IDecorBlock public class EdStairsBlock extends StandardStairsBlock implements IDecorBlock
{ {
public EdStairsBlock(long config, BlockState state, Block.Properties properties) public EdStairsBlock(long config, BlockState state, AbstractBlock.Properties properties)
{ super(config, state, properties); } { super(config, state, properties); }
public EdStairsBlock(long config, java.util.function.Supplier<BlockState> state, Block.Properties properties) public EdStairsBlock(long config, java.util.function.Supplier<BlockState> state, AbstractBlock.Properties properties)
{ super(config, state, properties); } { super(config, state, properties); }
} }

View file

@ -27,24 +27,26 @@ import javax.annotation.Nullable;
import java.util.Arrays; import java.util.Arrays;
import net.minecraft.block.AbstractBlock;
public class EdStraightPoleBlock extends DecorBlock.DirectedWaterLoggable implements IDecorBlock public class EdStraightPoleBlock extends DecorBlock.DirectedWaterLoggable implements IDecorBlock
{ {
private final EdStraightPoleBlock default_pole; private final EdStraightPoleBlock default_pole;
public EdStraightPoleBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB, @Nullable EdStraightPoleBlock defaultPole) public EdStraightPoleBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB, @Nullable EdStraightPoleBlock defaultPole)
{ super(config, builder, unrotatedAABB); default_pole=(defaultPole==null) ? (this) : (defaultPole); } { super(config, builder, unrotatedAABB); default_pole=(defaultPole==null) ? (this) : (defaultPole); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
Direction facing = context.getFace(); Direction facing = context.getClickedFace();
BlockState state = super.getStateForPlacement(context).with(FACING, facing); BlockState state = super.getStateForPlacement(context).setValue(FACING, facing);
if((config & DecorBlock.CFG_FLIP_PLACEMENT_IF_SAME) != 0) { if((config & DecorBlock.CFG_FLIP_PLACEMENT_IF_SAME) != 0) {
World world = context.getWorld(); World world = context.getLevel();
BlockPos pos = context.getPos(); BlockPos pos = context.getClickedPos();
if(world.getBlockState(pos.offset(facing.getOpposite())).getBlock() instanceof EdStraightPoleBlock) { if(world.getBlockState(pos.relative(facing.getOpposite())).getBlock() instanceof EdStraightPoleBlock) {
state = state.with(FACING, state.get(FACING).getOpposite()); state = state.setValue(FACING, state.getValue(FACING).getOpposite());
} }
} }
return state; return state;
@ -52,31 +54,31 @@ public class EdStraightPoleBlock extends DecorBlock.DirectedWaterLoggable implem
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
if((hit.getFace().getAxis() == state.get(FACING).getAxis())) return ActionResultType.PASS; if((hit.getDirection().getAxis() == state.getValue(FACING).getAxis())) return ActionResultType.PASS;
final ItemStack held_stack = player.getHeldItem(hand); final ItemStack held_stack = player.getItemInHand(hand);
if((held_stack.isEmpty()) || (!(held_stack.getItem() instanceof BlockItem))) return ActionResultType.PASS; if((held_stack.isEmpty()) || (!(held_stack.getItem() instanceof BlockItem))) return ActionResultType.PASS;
if(!(((BlockItem)(held_stack.getItem())).getBlock() instanceof EdStraightPoleBlock)) return ActionResultType.PASS; if(!(((BlockItem)(held_stack.getItem())).getBlock() instanceof EdStraightPoleBlock)) return ActionResultType.PASS;
if(held_stack.getItem() != default_pole.asItem()) return ActionResultType.func_233537_a_(world.isRemote()); if(held_stack.getItem() != default_pole.asItem()) return ActionResultType.sidedSuccess(world.isClientSide());
final Block held_block = ((BlockItem)(held_stack.getItem())).getBlock(); final Block held_block = ((BlockItem)(held_stack.getItem())).getBlock();
final Direction block_direction = state.get(FACING); final Direction block_direction = state.getValue(FACING);
final Vector3d block_vec = Vector3d.copy(state.get(FACING).getDirectionVec()); final Vector3d block_vec = Vector3d.atLowerCornerOf(state.getValue(FACING).getNormal());
final double colinearity = 1.0-block_vec.crossProduct(player.getLookVec()).length(); final double colinearity = 1.0-block_vec.cross(player.getLookAngle()).length();
final Direction placement_direction = Arrays.stream(Direction.getFacingDirections(player)).filter(d->d.getAxis()==block_direction.getAxis()).findFirst().orElse(Direction.NORTH); final Direction placement_direction = Arrays.stream(Direction.orderedByNearest(player)).filter(d->d.getAxis()==block_direction.getAxis()).findFirst().orElse(Direction.NORTH);
final BlockPos adjacent_pos = pos.offset(placement_direction); final BlockPos adjacent_pos = pos.relative(placement_direction);
final BlockState adjacent = world.getBlockState(adjacent_pos); final BlockState adjacent = world.getBlockState(adjacent_pos);
final BlockItemUseContext ctx = new DirectionalPlaceContext(world, adjacent_pos, placement_direction, player.getHeldItem(hand), placement_direction.getOpposite()); final BlockItemUseContext ctx = new DirectionalPlaceContext(world, adjacent_pos, placement_direction, player.getItemInHand(hand), placement_direction.getOpposite());
if(!adjacent.isReplaceable(ctx)) return ActionResultType.func_233537_a_(world.isRemote()); if(!adjacent.canBeReplaced(ctx)) return ActionResultType.sidedSuccess(world.isClientSide());
final BlockState new_state = held_block.getStateForPlacement(ctx); final BlockState new_state = held_block.getStateForPlacement(ctx);
if(new_state == null) return ActionResultType.FAIL; if(new_state == null) return ActionResultType.FAIL;
if(!world.setBlockState(adjacent_pos, new_state, 1|2)) return ActionResultType.FAIL; if(!world.setBlock(adjacent_pos, new_state, 1|2)) return ActionResultType.FAIL;
world.playSound(player, pos, SoundEvents.BLOCK_METAL_PLACE, SoundCategory.BLOCKS, 1f, 1f); world.playSound(player, pos, SoundEvents.METAL_PLACE, SoundCategory.BLOCKS, 1f, 1f);
if(!player.isCreative()) { if(!player.isCreative()) {
held_stack.shrink(1); held_stack.shrink(1);
Inventories.setItemInPlayerHand(player, hand, held_stack); Inventories.setItemInPlayerHand(player, hand, held_stack);
} }
return ActionResultType.func_233537_a_(world.isRemote()); return ActionResultType.sidedSuccess(world.isClientSide());
} }
} }

View file

@ -17,7 +17,7 @@ import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorldReader; import net.minecraft.world.IWorldReader;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.block.Block; import net.minecraft.block.AbstractBlock;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.tileentity.TileEntityType; import net.minecraft.tileentity.TileEntityType;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
@ -58,12 +58,12 @@ public class EdTestBlock
public static class TestBlock extends DecorBlock.Directed implements Auxiliaries.IExperimentalFeature, IDecorBlock public static class TestBlock extends DecorBlock.Directed implements Auxiliaries.IExperimentalFeature, IDecorBlock
{ {
public TestBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB) public TestBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return VoxelShapes.fullCube(); } { return VoxelShapes.block(); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -92,10 +92,10 @@ public class EdTestBlock
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof TestTileEntity)) return ActionResultType.FAIL; if(!(te instanceof TestTileEntity)) return ActionResultType.FAIL;
return ((TestTileEntity)te).activated(player, hand, hit) ? ActionResultType.CONSUME : ActionResultType.PASS; return ((TestTileEntity)te).activated(player, hand, hit) ? ActionResultType.CONSUME : ActionResultType.PASS;
} }
@ -147,9 +147,9 @@ public class EdTestBlock
} }
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ {
super.read(state, nbt); super.load(state, nbt);
tank_.load(nbt); tank_.load(nbt);
battery_.load(nbt); battery_.load(nbt);
rf_fed_avg = nbt.getInt("rf_fed_avg"); rf_fed_avg = nbt.getInt("rf_fed_avg");
@ -166,13 +166,13 @@ public class EdTestBlock
items_received_total = nbt.getInt("items_received_total"); items_received_total = nbt.getInt("items_received_total");
items_inserted_total = nbt.getInt("items_inserted_total"); items_inserted_total = nbt.getInt("items_inserted_total");
if(nbt.contains("liq_fill_stack")) liq_fill_stack = FluidStack.loadFluidStackFromNBT(nbt.getCompound("liq_fill_stack")); if(nbt.contains("liq_fill_stack")) liq_fill_stack = FluidStack.loadFluidStackFromNBT(nbt.getCompound("liq_fill_stack"));
if(nbt.contains("insertion_item")) insertion_item = ItemStack.read(nbt.getCompound("insertion_item")); if(nbt.contains("insertion_item")) insertion_item = ItemStack.of(nbt.getCompound("insertion_item"));
} }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ {
super.write(nbt); super.save(nbt);
tank_.save(nbt); tank_.save(nbt);
battery_.save(nbt); battery_.save(nbt);
nbt.putInt("rf_fed_avg", rf_fed_avg); nbt.putInt("rf_fed_avg", rf_fed_avg);
@ -189,7 +189,7 @@ public class EdTestBlock
nbt.putInt("items_received_total", items_received_total); nbt.putInt("items_received_total", items_received_total);
nbt.putInt("items_inserted_total", items_inserted_total); nbt.putInt("items_inserted_total", items_inserted_total);
if(!liq_fill_stack.isEmpty()) nbt.put("liq_fill_stack", liq_fill_stack.writeToNBT(new CompoundNBT())); if(!liq_fill_stack.isEmpty()) nbt.put("liq_fill_stack", liq_fill_stack.writeToNBT(new CompoundNBT()));
if(!insertion_item.isEmpty()) nbt.put("insertion_item", insertion_item.write(new CompoundNBT())); if(!insertion_item.isEmpty()) nbt.put("insertion_item", insertion_item.save(new CompoundNBT()));
return nbt; return nbt;
} }
@ -211,7 +211,7 @@ public class EdTestBlock
public boolean activated(PlayerEntity player, Hand hand, BlockRayTraceResult hit) public boolean activated(PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
final ItemStack held = player.getHeldItem(hand); final ItemStack held = player.getItemInHand(hand);
if(held.isEmpty()) { if(held.isEmpty()) {
ArrayList<String> msgs = new ArrayList<>(); ArrayList<String> msgs = new ArrayList<>();
if(rf_fed_avg > 0) msgs.add("-" + rf_fed_avg + "rf/t"); if(rf_fed_avg > 0) msgs.add("-" + rf_fed_avg + "rf/t");
@ -248,7 +248,7 @@ public class EdTestBlock
if(rf_feed_setting == 0) rf_feed_setting = 0x10; if(rf_feed_setting == 0) rf_feed_setting = 0x10;
Overlay.show(player, new StringTextComponent("RF feed rate: " + rf_feed_setting + "rf/t"), 1000); Overlay.show(player, new StringTextComponent("RF feed rate: " + rf_feed_setting + "rf/t"), 1000);
} else { } else {
BlockState adjacent_state = world.getBlockState(pos.offset(block_facing)); BlockState adjacent_state = level.getBlockState(worldPosition.relative(block_facing));
if(adjacent_state.getBlock()==Blocks.HOPPER || adjacent_state.getBlock()==ModContent.FACTORY_HOPPER) { if(adjacent_state.getBlock()==Blocks.HOPPER || adjacent_state.getBlock()==ModContent.FACTORY_HOPPER) {
insertion_item = held.copy(); insertion_item = held.copy();
Overlay.show(player, new StringTextComponent("Insertion item: " + (insertion_item.getItem()==Items.LEVER ? "random" : insertion_item.toString()) + "/s"), 1000); Overlay.show(player, new StringTextComponent("Insertion item: " + (insertion_item.getItem()==Items.LEVER ? "random" : insertion_item.toString()) + "/s"), 1000);
@ -261,9 +261,9 @@ public class EdTestBlock
} }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
energy_handler_.invalidate(); energy_handler_.invalidate();
fluid_handler_.invalidate(); fluid_handler_.invalidate();
item_handler_.invalidate(); item_handler_.invalidate();
@ -283,39 +283,39 @@ public class EdTestBlock
@Override @Override
public void tick() public void tick()
{ {
if(world.isRemote()) return; if(level.isClientSide()) return;
block_facing = getBlockState().get(TestBlock.FACING); block_facing = getBlockState().getValue(TestBlock.FACING);
paused = world.isBlockPowered(getPos()); paused = level.hasNeighborSignal(getBlockPos());
if(!paused) { if(!paused) {
boolean dirty = false; boolean dirty = false;
{ {
int p = RfEnergy.feed(getWorld(), getPos().offset(block_facing), block_facing.getOpposite(), rf_feed_setting); int p = RfEnergy.feed(getLevel(), getBlockPos().relative(block_facing), block_facing.getOpposite(), rf_feed_setting);
rf_fed_acc += p; rf_fed_acc += p;
dirty |= p>0; dirty |= p>0;
} }
if(!liq_fill_stack.isEmpty()) { if(!liq_fill_stack.isEmpty()) {
int f = Fluidics.fill(getWorld(), getPos().offset(block_facing), block_facing.getOpposite(), liq_fill_stack); int f = Fluidics.fill(getLevel(), getBlockPos().relative(block_facing), block_facing.getOpposite(), liq_fill_stack);
liq_filled_acc += f; liq_filled_acc += f;
dirty |= f>0; dirty |= f>0;
} }
if(!inventory_.isEmpty()) { if(!inventory_.isEmpty()) {
int i = inventory_.getStackInSlot(0).getCount(); int i = inventory_.getItem(0).getCount();
items_received_total += i; items_received_total += i;
inventory_.clear(); inventory_.clearContent();
dirty |= i>0; dirty |= i>0;
} }
if((tick_timer == 1) && (!insertion_item.isEmpty())) { if((tick_timer == 1) && (!insertion_item.isEmpty())) {
BlockState adjacent_state = world.getBlockState(pos.offset(block_facing)); BlockState adjacent_state = level.getBlockState(worldPosition.relative(block_facing));
ItemStack stack = (insertion_item.getItem()==Items.LEVER) ? getRandomItemstack() : insertion_item.copy(); ItemStack stack = (insertion_item.getItem()==Items.LEVER) ? getRandomItemstack() : insertion_item.copy();
if(adjacent_state.getBlock()==Blocks.HOPPER || adjacent_state.getBlock()==ModContent.FACTORY_HOPPER) { if(adjacent_state.getBlock()==Blocks.HOPPER || adjacent_state.getBlock()==ModContent.FACTORY_HOPPER) {
ItemStack remaining = Inventories.insert(getWorld(), getPos().offset(block_facing), block_facing.getOpposite(), stack, false); ItemStack remaining = Inventories.insert(getLevel(), getBlockPos().relative(block_facing), block_facing.getOpposite(), stack, false);
int n = stack.getCount() - remaining.getCount(); int n = stack.getCount() - remaining.getCount();
items_inserted_total += n; items_inserted_total += n;
dirty |= n>0; dirty |= n>0;
} }
} }
if(dirty) { if(dirty) {
markDirty(); setChanged();
} }
} }
if(--tick_timer <= 0) { if(--tick_timer <= 0) {

View file

@ -11,6 +11,7 @@ package wile.engineersdecor.blocks;
import net.minecraft.world.IWorldReader; import net.minecraft.world.IWorldReader;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.state.BooleanProperty; import net.minecraft.state.BooleanProperty;
@ -42,6 +43,7 @@ import javax.annotation.Nullable;
import java.util.Random; import java.util.Random;
public class EdTreeCutter public class EdTreeCutter
{ {
public static void on_config(int boost_energy_per_tick, int cutting_time_seconds, boolean power_required) public static void on_config(int boost_energy_per_tick, int cutting_time_seconds, boolean power_required)
@ -55,17 +57,17 @@ public class EdTreeCutter
{ {
public static final BooleanProperty ACTIVE = BooleanProperty.create("active"); public static final BooleanProperty ACTIVE = BooleanProperty.create("active");
public TreeCutterBlock(long config, Block.Properties builder, final AxisAlignedBB[] unrotatedAABB) public TreeCutterBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB[] unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(ACTIVE); } { super.createBlockStateDefinition(builder); builder.add(ACTIVE); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(ACTIVE, false); } { return super.getStateForPlacement(context).setValue(ACTIVE, false); }
@Override @Override
public boolean hasTileEntity(BlockState state) public boolean hasTileEntity(BlockState state)
@ -79,12 +81,12 @@ public class EdTreeCutter
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void animateTick(BlockState state, World world, BlockPos pos, Random rnd) public void animateTick(BlockState state, World world, BlockPos pos, Random rnd)
{ {
if((state.getBlock()!=this) || (!state.get(ACTIVE))) return; if((state.getBlock()!=this) || (!state.getValue(ACTIVE))) return;
final double rv = rnd.nextDouble(); final double rv = rnd.nextDouble();
if(rv > 0.8) return; if(rv > 0.8) return;
final double x=0.5+pos.getX(), y=0.5+pos.getY(), z=0.5+pos.getZ(); final double x=0.5+pos.getX(), y=0.5+pos.getY(), z=0.5+pos.getZ();
final double xc=0.52, xr=rnd.nextDouble()*0.4-0.2, yr=(y-0.3+rnd.nextDouble()*0.2); final double xc=0.52, xr=rnd.nextDouble()*0.4-0.2, yr=(y-0.3+rnd.nextDouble()*0.2);
switch(state.get(HORIZONTAL_FACING)) { switch(state.getValue(HORIZONTAL_FACING)) {
case WEST: world.addParticle(ParticleTypes.SMOKE, x-xc, yr, z+xr, 0.0, 0.0, 0.0); break; case WEST: world.addParticle(ParticleTypes.SMOKE, x-xc, yr, z+xr, 0.0, 0.0, 0.0); break;
case EAST: world.addParticle(ParticleTypes.SMOKE, x+xc, yr, z+xr, 0.0, 0.0, 0.0); break; case EAST: world.addParticle(ParticleTypes.SMOKE, x+xc, yr, z+xr, 0.0, 0.0, 0.0); break;
case NORTH: world.addParticle(ParticleTypes.SMOKE, x+xr, yr, z-xc, 0.0, 0.0, 0.0); break; case NORTH: world.addParticle(ParticleTypes.SMOKE, x+xr, yr, z-xc, 0.0, 0.0, 0.0); break;
@ -94,10 +96,10 @@ public class EdTreeCutter
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(te instanceof TreeCutterTileEntity) ((TreeCutterTileEntity)te).state_message(player); if(te instanceof TreeCutterTileEntity) ((TreeCutterTileEntity)te).state_message(player);
return ActionResultType.CONSUME; return ActionResultType.CONSUME;
} }
@ -162,17 +164,17 @@ public class EdTreeCutter
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); writenbt(nbt); return nbt; } { super.save(nbt); writenbt(nbt); return nbt; }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
energy_handler_.invalidate(); energy_handler_.invalidate();
} }
@ -223,21 +225,21 @@ public class EdTreeCutter
public void tick() public void tick()
{ {
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
final BlockState device_state = world.getBlockState(pos); final BlockState device_state = level.getBlockState(worldPosition);
if(!(device_state.getBlock() instanceof TreeCutterBlock)) { tick_timer_ = TICK_INTERVAL; return; } if(!(device_state.getBlock() instanceof TreeCutterBlock)) { tick_timer_ = TICK_INTERVAL; return; }
if(world.isRemote) { if(level.isClientSide) {
if(!device_state.get(TreeCutterBlock.ACTIVE)) { if(!device_state.getValue(TreeCutterBlock.ACTIVE)) {
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
} else { } else {
tick_timer_ = 1; tick_timer_ = 1;
world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.BLOCK_WOOD_HIT, SoundCategory.BLOCKS, 0.1f, 1.0f, false); level.playLocalSound(worldPosition.getX(), worldPosition.getY(), worldPosition.getZ(), SoundEvents.WOOD_HIT, SoundCategory.BLOCKS, 0.1f, 1.0f, false);
} }
} else { } else {
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
final BlockPos tree_pos = pos.offset(device_state.get(TreeCutterBlock.HORIZONTAL_FACING)); final BlockPos tree_pos = worldPosition.relative(device_state.getValue(TreeCutterBlock.HORIZONTAL_FACING));
final BlockState tree_state = world.getBlockState(tree_pos); final BlockState tree_state = level.getBlockState(tree_pos);
if(!TreeCutting.canChop(tree_state) || (world.isBlockPowered(pos))) { if(!TreeCutting.canChop(tree_state) || (level.hasNeighborSignal(worldPosition))) {
if(device_state.get(TreeCutterBlock.ACTIVE)) world.setBlockState(pos, device_state.with(TreeCutterBlock.ACTIVE, false), 1|2); if(device_state.getValue(TreeCutterBlock.ACTIVE)) level.setBlock(worldPosition, device_state.setValue(TreeCutterBlock.ACTIVE, false), 1|2);
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
active_timer_ = 0; active_timer_ = 0;
tick_timer_ = IDLE_TICK_INTERVAL; tick_timer_ = IDLE_TICK_INTERVAL;
@ -259,12 +261,12 @@ public class EdTreeCutter
} }
if(proc_time_elapsed_ >= cutting_time_needed) { if(proc_time_elapsed_ >= cutting_time_needed) {
proc_time_elapsed_ = 0; proc_time_elapsed_ = 0;
TreeCutting.chopTree(world, tree_state, tree_pos, 512, false); TreeCutting.chopTree(level, tree_state, tree_pos, 512, false);
world.playSound(null, pos.getX(), pos.getY(), pos.getZ(), SoundEvents.BLOCK_WOOD_BREAK, SoundCategory.BLOCKS, 1.0f, 1.0f); level.playSound(null, worldPosition.getX(), worldPosition.getY(), worldPosition.getZ(), SoundEvents.WOOD_BREAK, SoundCategory.BLOCKS, 1.0f, 1.0f);
active = false; active = false;
} }
if(device_state.get(TreeCutterBlock.ACTIVE) != active) { if(device_state.getValue(TreeCutterBlock.ACTIVE) != active) {
world.setBlockState(pos, device_state.with(TreeCutterBlock.ACTIVE, active), 1|2); level.setBlock(worldPosition, device_state.setValue(TreeCutterBlock.ACTIVE, active), 1|2);
} }
} }
} }

View file

@ -17,7 +17,7 @@ import wile.engineersdecor.libmc.blocks.VariantWallBlock;
public class EdWallBlock extends VariantWallBlock implements IDecorBlock public class EdWallBlock extends VariantWallBlock implements IDecorBlock
{ {
public EdWallBlock(long config, Block.Properties builder) public EdWallBlock(long config, AbstractBlock.Properties builder)
{ super(config, builder); } { super(config, builder); }
protected boolean attachesTo(BlockState facingState, IWorldReader world, BlockPos facingPos, Direction side) protected boolean attachesTo(BlockState facingState, IWorldReader world, BlockPos facingPos, Direction side)

View file

@ -21,6 +21,7 @@ import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.world.IWorldReader; import net.minecraft.world.IWorldReader;
@ -76,27 +77,27 @@ public class EdWasteIncinerator
{ {
public static final BooleanProperty LIT = FurnaceBlock.LIT; public static final BooleanProperty LIT = FurnaceBlock.LIT;
public WasteIncineratorBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB) public WasteIncineratorBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(LIT); } { super.createBlockStateDefinition(builder); builder.add(LIT); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(LIT, false); } { return super.getStateForPlacement(context).setValue(LIT, false); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(BlockState state) public boolean hasAnalogOutputSignal(BlockState state)
{ return true; } { return true; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int getComparatorInputOverride(BlockState blockState, World world, BlockPos pos) public int getAnalogOutputSignal(BlockState blockState, World world, BlockPos pos)
{ return Container.calcRedstone(world.getTileEntity(pos)); } { return Container.getRedstoneSignalFromBlockEntity(world.getBlockEntity(pos)); }
@Override @Override
public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side) public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
@ -112,16 +113,16 @@ public class EdWasteIncinerator
{ return new EdWasteIncinerator.WasteIncineratorTileEntity(); } { return new EdWasteIncinerator.WasteIncineratorTileEntity(); }
@Override @Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) public void setPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{ {
if(world.isRemote) return; if(world.isClientSide) return;
if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return; if((!stack.hasTag()) || (!stack.getTag().contains("tedata"))) return;
CompoundNBT te_nbt = stack.getTag().getCompound("tedata"); CompoundNBT te_nbt = stack.getTag().getCompound("tedata");
if(te_nbt.isEmpty()) return; if(te_nbt.isEmpty()) return;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof EdWasteIncinerator.WasteIncineratorTileEntity)) return; if(!(te instanceof EdWasteIncinerator.WasteIncineratorTileEntity)) return;
((EdWasteIncinerator.WasteIncineratorTileEntity)te).readnbt(te_nbt); ((EdWasteIncinerator.WasteIncineratorTileEntity)te).readnbt(te_nbt);
((EdWasteIncinerator.WasteIncineratorTileEntity)te).markDirty(); ((EdWasteIncinerator.WasteIncineratorTileEntity)te).setChanged();
} }
@Override @Override
@ -132,7 +133,7 @@ public class EdWasteIncinerator
public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, final TileEntity te, boolean explosion)
{ {
final List<ItemStack> stacks = new ArrayList<ItemStack>(); final List<ItemStack> stacks = new ArrayList<ItemStack>();
if(world.isRemote) return stacks; if(world.isClientSide) return stacks;
if(!(te instanceof WasteIncineratorTileEntity)) return stacks; if(!(te instanceof WasteIncineratorTileEntity)) return stacks;
if(!explosion) { if(!explosion) {
ItemStack stack = new ItemStack(this, 1); ItemStack stack = new ItemStack(this, 1);
@ -152,10 +153,10 @@ public class EdWasteIncinerator
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult)
{ {
if(world.isRemote()) return ActionResultType.SUCCESS; if(world.isClientSide()) return ActionResultType.SUCCESS;
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(!(te instanceof WasteIncineratorTileEntity)) return ActionResultType.FAIL; if(!(te instanceof WasteIncineratorTileEntity)) return ActionResultType.FAIL;
if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL; if((!(player instanceof ServerPlayerEntity) && (!(player instanceof FakePlayer)))) return ActionResultType.FAIL;
NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te); NetworkHooks.openGui((ServerPlayerEntity)player,(INamedContainerProvider)te);
@ -166,7 +167,7 @@ public class EdWasteIncinerator
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void animateTick(BlockState state, World world, BlockPos pos, Random rnd) public void animateTick(BlockState state, World world, BlockPos pos, Random rnd)
{ {
if((state.getBlock()!=this) || (!state.get(LIT))) return; if((state.getBlock()!=this) || (!state.getValue(LIT))) return;
final double rv = rnd.nextDouble(); final double rv = rnd.nextDouble();
if(rv > 0.5) return; if(rv > 0.5) return;
final double x=0.5+pos.getX(), y=0.5+pos.getY(), z=0.5+pos.getZ(); final double x=0.5+pos.getX(), y=0.5+pos.getY(), z=0.5+pos.getZ();
@ -244,17 +245,17 @@ public class EdWasteIncinerator
// TileEntity ------------------------------------------------------------------------------ // TileEntity ------------------------------------------------------------------------------
@Override @Override
public void read(BlockState state, CompoundNBT nbt) public void load(BlockState state, CompoundNBT nbt)
{ super.read(state, nbt); readnbt(nbt); } { super.load(state, nbt); readnbt(nbt); }
@Override @Override
public CompoundNBT write(CompoundNBT nbt) public CompoundNBT save(CompoundNBT nbt)
{ super.write(nbt); return writenbt(nbt); } { super.save(nbt); return writenbt(nbt); }
@Override @Override
public void remove() public void setRemoved()
{ {
super.remove(); super.setRemoved();
energy_handler_.invalidate(); energy_handler_.invalidate();
item_handler_.invalidate(); item_handler_.invalidate();
} }
@ -263,7 +264,7 @@ public class EdWasteIncinerator
@Override @Override
public ITextComponent getName() public ITextComponent getName()
{ final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getTranslationKey() : "Small Waste Incinerator"); } { final Block block=getBlockState().getBlock(); return new StringTextComponent((block!=null) ? block.getDescriptionId() : "Small Waste Incinerator"); }
@Override @Override
public boolean hasCustomName() public boolean hasCustomName()
@ -281,12 +282,12 @@ public class EdWasteIncinerator
@Override @Override
public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player ) public Container createMenu(int id, PlayerInventory inventory, PlayerEntity player )
{ return new EdWasteIncinerator.WasteIncineratorContainer(id, inventory, this, IWorldPosCallable.of(world, pos), fields); } { return new EdWasteIncinerator.WasteIncineratorContainer(id, inventory, this, IWorldPosCallable.create(level, worldPosition), fields); }
// IInventory ------------------------------------------------------------------------------ // IInventory ------------------------------------------------------------------------------
@Override @Override
public int getSizeInventory() public int getContainerSize()
{ return stacks_.size(); } { return stacks_.size(); }
@Override @Override
@ -294,51 +295,51 @@ public class EdWasteIncinerator
{ for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; } { for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; }
@Override @Override
public ItemStack getStackInSlot(int index) public ItemStack getItem(int index)
{ return ((index >= 0) && (index < getSizeInventory())) ? stacks_.get(index) : ItemStack.EMPTY; } { return ((index >= 0) && (index < getContainerSize())) ? stacks_.get(index) : ItemStack.EMPTY; }
@Override @Override
public ItemStack decrStackSize(int index, int count) public ItemStack removeItem(int index, int count)
{ return ItemStackHelper.getAndSplit(stacks_, index, count); } { return ItemStackHelper.removeItem(stacks_, index, count); }
@Override @Override
public ItemStack removeStackFromSlot(int index) public ItemStack removeItemNoUpdate(int index)
{ return ItemStackHelper.getAndRemove(stacks_, index); } { return ItemStackHelper.takeItem(stacks_, index); }
@Override @Override
public void setInventorySlotContents(int index, ItemStack stack) public void setItem(int index, ItemStack stack)
{ {
if(stack.getCount() > getInventoryStackLimit()) stack.setCount(getInventoryStackLimit()); if(stack.getCount() > getMaxStackSize()) stack.setCount(getMaxStackSize());
stacks_.set(index, stack); stacks_.set(index, stack);
markDirty(); setChanged();
} }
@Override @Override
public int getInventoryStackLimit() public int getMaxStackSize()
{ return 64; } { return 64; }
@Override @Override
public void markDirty() public void setChanged()
{ super.markDirty(); } { super.setChanged(); }
@Override @Override
public boolean isUsableByPlayer(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return ((getWorld().getTileEntity(getPos()) == this)) && (getPos().distanceSq(player.getPosition()) < 64); } { return ((getLevel().getBlockEntity(getBlockPos()) == this)) && (getBlockPos().distSqr(player.blockPosition()) < 64); }
@Override @Override
public void openInventory(PlayerEntity player) public void startOpen(PlayerEntity player)
{} {}
@Override @Override
public void closeInventory(PlayerEntity player) public void stopOpen(PlayerEntity player)
{ markDirty(); } { setChanged(); }
@Override @Override
public boolean isItemValidForSlot(int index, ItemStack stack) public boolean canPlaceItem(int index, ItemStack stack)
{ return (index==0); } { return (index==0); }
@Override @Override
public void clear() public void clearContent()
{ stacks_.clear(); } { stacks_.clear(); }
// Fields ----------------------------------------------------------------------------------------------- // Fields -----------------------------------------------------------------------------------------------
@ -370,11 +371,11 @@ public class EdWasteIncinerator
{ return SIDED_INV_SLOTS; } { return SIDED_INV_SLOTS; }
@Override @Override
public boolean canInsertItem(int index, ItemStack itemStackIn, Direction direction) public boolean canPlaceItemThroughFace(int index, ItemStack itemStackIn, Direction direction)
{ return isItemValidForSlot(index, itemStackIn); } { return canPlaceItem(index, itemStackIn); }
@Override @Override
public boolean canExtractItem(int index, ItemStack stack, Direction direction) public boolean canTakeItemThroughFace(int index, ItemStack stack, Direction direction)
{ return false; } { return false; }
// IEnergyStorage ---------------------------------------------------------------------------- // IEnergyStorage ----------------------------------------------------------------------------
@ -405,7 +406,7 @@ public class EdWasteIncinerator
if(energy_stored_ >= MAX_ENERGY_BUFFER) return 0; if(energy_stored_ >= MAX_ENERGY_BUFFER) return 0;
int n = Math.min(maxReceive, (MAX_ENERGY_BUFFER - energy_stored_)); int n = Math.min(maxReceive, (MAX_ENERGY_BUFFER - energy_stored_));
if(n > MAX_ENERGY_TRANSFER) n = MAX_ENERGY_TRANSFER; if(n > MAX_ENERGY_TRANSFER) n = MAX_ENERGY_TRANSFER;
if(!simulate) {energy_stored_ += n; markDirty(); } if(!simulate) {energy_stored_ += n; setChanged(); }
return n; return n;
} }
@ -413,7 +414,7 @@ public class EdWasteIncinerator
protected static class BItemHandler implements IItemHandler protected static class BItemHandler implements IItemHandler
{ {
private WasteIncineratorTileEntity te; private final WasteIncineratorTileEntity te;
BItemHandler(WasteIncineratorTileEntity te) BItemHandler(WasteIncineratorTileEntity te)
{ this.te = te; } { this.te = te; }
@ -424,7 +425,7 @@ public class EdWasteIncinerator
@Override @Override
public int getSlotLimit(int index) public int getSlotLimit(int index)
{ return te.getInventoryStackLimit(); } { return te.getMaxStackSize(); }
@Override @Override
public boolean isItemValid(int slot, @Nonnull ItemStack stack) public boolean isItemValid(int slot, @Nonnull ItemStack stack)
@ -442,13 +443,13 @@ public class EdWasteIncinerator
{ {
if(slotstack.getCount() >= Math.min(slotstack.getMaxStackSize(), getSlotLimit(index))) return stack; if(slotstack.getCount() >= Math.min(slotstack.getMaxStackSize(), getSlotLimit(index))) return stack;
if(!ItemHandlerHelper.canItemStacksStack(stack, slotstack)) return stack; if(!ItemHandlerHelper.canItemStacksStack(stack, slotstack)) return stack;
if(!te.canInsertItem(slotno, stack, Direction.UP) || (!te.isItemValidForSlot(slotno, stack))) return stack; if(!te.canPlaceItemThroughFace(slotno, stack, Direction.UP) || (!te.canPlaceItem(slotno, stack))) return stack;
int n = Math.min(stack.getMaxStackSize(), getSlotLimit(index)) - slotstack.getCount(); int n = Math.min(stack.getMaxStackSize(), getSlotLimit(index)) - slotstack.getCount();
if(stack.getCount() <= n) { if(stack.getCount() <= n) {
if(!simulate) { if(!simulate) {
ItemStack copy = stack.copy(); ItemStack copy = stack.copy();
copy.grow(slotstack.getCount()); copy.grow(slotstack.getCount());
te.setInventorySlotContents(slotno, copy); te.setItem(slotno, copy);
} }
return ItemStack.EMPTY; return ItemStack.EMPTY;
} else { } else {
@ -456,7 +457,7 @@ public class EdWasteIncinerator
if(!simulate) { if(!simulate) {
ItemStack copy = stack.split(n); ItemStack copy = stack.split(n);
copy.grow(slotstack.getCount()); copy.grow(slotstack.getCount());
te.setInventorySlotContents(slotno, copy); te.setItem(slotno, copy);
return stack; return stack;
} else { } else {
stack.shrink(n); stack.shrink(n);
@ -464,19 +465,19 @@ public class EdWasteIncinerator
} }
} }
} else { } else {
if(!te.canInsertItem(slotno, stack, Direction.UP) || (!te.isItemValidForSlot(slotno, stack))) return stack; if(!te.canPlaceItemThroughFace(slotno, stack, Direction.UP) || (!te.canPlaceItem(slotno, stack))) return stack;
int n = Math.min(stack.getMaxStackSize(), getSlotLimit(index)); int n = Math.min(stack.getMaxStackSize(), getSlotLimit(index));
if(n < stack.getCount()) { if(n < stack.getCount()) {
stack = stack.copy(); stack = stack.copy();
if(!simulate) { if(!simulate) {
te.setInventorySlotContents(slotno, stack.split(n)); te.setItem(slotno, stack.split(n));
return stack; return stack;
} else { } else {
stack.shrink(n); stack.shrink(n);
return stack; return stack;
} }
} else { } else {
if(!simulate) te.setInventorySlotContents(slotno, stack); if(!simulate) te.setItem(slotno, stack);
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
} }
@ -490,7 +491,7 @@ public class EdWasteIncinerator
@Override @Override
@Nonnull @Nonnull
public ItemStack getStackInSlot(int index) public ItemStack getStackInSlot(int index)
{ return te.getStackInSlot(index); } { return te.getItem(index); }
} }
// Capability export ---------------------------------------------------------------------------- // Capability export ----------------------------------------------------------------------------
@ -513,13 +514,13 @@ public class EdWasteIncinerator
{ {
if(--tick_timer_ > 0) return; if(--tick_timer_ > 0) return;
tick_timer_ = TICK_INTERVAL; tick_timer_ = TICK_INTERVAL;
if(world.isRemote) return; if(level.isClientSide) return;
boolean dirty = false; boolean dirty = false;
ItemStack processing_stack = stacks_.get(BURN_SLOT_NO); ItemStack processing_stack = stacks_.get(BURN_SLOT_NO);
final boolean was_processing = !processing_stack.isEmpty(); final boolean was_processing = !processing_stack.isEmpty();
boolean is_processing = was_processing; boolean is_processing = was_processing;
boolean new_stack_processing = false; boolean new_stack_processing = false;
if((!stacks_.get(0).isEmpty()) && transferItems(0, 1, getInventoryStackLimit())) dirty = true; if((!stacks_.get(0).isEmpty()) && transferItems(0, 1, getMaxStackSize())) dirty = true;
ItemStack first_stack = stacks_.get(0); ItemStack first_stack = stacks_.get(0);
boolean shift = !first_stack.isEmpty(); boolean shift = !first_stack.isEmpty();
if(is_processing) { if(is_processing) {
@ -538,7 +539,7 @@ public class EdWasteIncinerator
if(shift) { if(shift) {
boolean transferred = false; boolean transferred = false;
for(int i=BURN_SLOT_NO-1; i>0; --i) { for(int i=BURN_SLOT_NO-1; i>0; --i) {
transferred |= transferItems(i-1, i, getInventoryStackLimit()); transferred |= transferItems(i-1, i, getMaxStackSize());
} }
if((!is_processing) && (!transferred)) { if((!is_processing) && (!transferred)) {
shiftStacks(0, BURN_SLOT_NO); shiftStacks(0, BURN_SLOT_NO);
@ -546,13 +547,13 @@ public class EdWasteIncinerator
} }
} }
if((was_processing != is_processing) || (new_stack_processing)) { if((was_processing != is_processing) || (new_stack_processing)) {
if(new_stack_processing) world.playSound(null, pos, SoundEvents.BLOCK_LAVA_AMBIENT, SoundCategory.BLOCKS, 0.05f, 2.4f); if(new_stack_processing) level.playSound(null, worldPosition, SoundEvents.LAVA_AMBIENT, SoundCategory.BLOCKS, 0.05f, 2.4f);
final BlockState state = world.getBlockState(pos); final BlockState state = level.getBlockState(worldPosition);
if(state.getBlock() instanceof WasteIncineratorBlock) { if(state.getBlock() instanceof WasteIncineratorBlock) {
world.setBlockState(pos, state.with(WasteIncineratorBlock.LIT, is_processing), 2|16); level.setBlock(worldPosition, state.setValue(WasteIncineratorBlock.LIT, is_processing), 2|16);
} }
} }
if(dirty) markDirty(); if(dirty) setChanged();
} }
// Aux methods ---------------------------------------------------------------------------------- // Aux methods ----------------------------------------------------------------------------------
@ -618,10 +619,10 @@ public class EdWasteIncinerator
public int field(int index) { return fields_.get(index); } public int field(int index) { return fields_.get(index); }
public PlayerEntity player() { return player_ ; } public PlayerEntity player() { return player_ ; }
public IInventory inventory() { return inventory_ ; } public IInventory inventory() { return inventory_ ; }
public World world() { return player_.world; } public World world() { return player_.level; }
public WasteIncineratorContainer(int cid, PlayerInventory player_inventory) public WasteIncineratorContainer(int cid, PlayerInventory player_inventory)
{ this(cid, player_inventory, new Inventory(WasteIncineratorTileEntity.NUM_OF_SLOTS), IWorldPosCallable.DUMMY, new IntArray(WasteIncineratorTileEntity.NUM_OF_FIELDS)); } { this(cid, player_inventory, new Inventory(WasteIncineratorTileEntity.NUM_OF_SLOTS), IWorldPosCallable.NULL, new IntArray(WasteIncineratorTileEntity.NUM_OF_FIELDS)); }
private WasteIncineratorContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields) private WasteIncineratorContainer(int cid, PlayerInventory player_inventory, IInventory block_inventory, IWorldPosCallable wpc, IIntArray fields)
{ {
@ -658,30 +659,30 @@ public class EdWasteIncinerator
} }
@Override @Override
public boolean canInteractWith(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return inventory_.isUsableByPlayer(player); } { return inventory_.stillValid(player); }
@Override @Override
public ItemStack transferStackInSlot(PlayerEntity player, int index) public ItemStack quickMoveStack(PlayerEntity player, int index)
{ {
Slot slot = getSlot(index); Slot slot = getSlot(index);
if((slot==null) || (!slot.getHasStack())) return ItemStack.EMPTY; if((slot==null) || (!slot.hasItem())) return ItemStack.EMPTY;
ItemStack slot_stack = slot.getStack(); ItemStack slot_stack = slot.getItem();
ItemStack transferred = slot_stack.copy(); ItemStack transferred = slot_stack.copy();
if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) { if((index>=0) && (index<PLAYER_INV_START_SLOTNO)) {
// Device slots // Device slots
if(!mergeItemStack(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, true)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, PLAYER_INV_START_SLOTNO, PLAYER_INV_START_SLOTNO+36, true)) return ItemStack.EMPTY;
} else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) { } else if((index >= PLAYER_INV_START_SLOTNO) && (index <= PLAYER_INV_START_SLOTNO+36)) {
// Player slot // Player slot
if(!mergeItemStack(slot_stack, 0, PLAYER_INV_START_SLOTNO-1, true)) return ItemStack.EMPTY; if(!moveItemStackTo(slot_stack, 0, PLAYER_INV_START_SLOTNO-1, true)) return ItemStack.EMPTY;
} else { } else {
// invalid slot // invalid slot
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
if(slot_stack.isEmpty()) { if(slot_stack.isEmpty()) {
slot.putStack(ItemStack.EMPTY); slot.set(ItemStack.EMPTY);
} else { } else {
slot.onSlotChanged(); slot.setChanged();
} }
if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY; if(slot_stack.getCount() == transferred.getCount()) return ItemStack.EMPTY;
slot.onTake(player, slot_stack); slot.onTake(player, slot_stack);
@ -710,21 +711,21 @@ public class EdWasteIncinerator
{ {
renderBackground/*renderBackground*/(mx); renderBackground/*renderBackground*/(mx);
super.render(mx, mouseX, mouseY, partialTicks); super.render(mx, mouseX, mouseY, partialTicks);
renderHoveredTooltip(mx, mouseX, mouseY); renderTooltip(mx, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerForegroundLayer(MatrixStack mx, int x, int y) protected void renderLabels(MatrixStack mx, int x, int y)
{} {}
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void drawGuiContainerBackgroundLayer(MatrixStack mx, float partialTicks, int mouseX, int mouseY) protected void renderBg(MatrixStack mx, float partialTicks, int mouseX, int mouseY)
{ {
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
getMinecraft().getTextureManager().bindTexture(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/small_waste_incinerator_gui.png")); getMinecraft().getTextureManager().bind(new ResourceLocation(ModEngineersDecor.MODID, "textures/gui/small_waste_incinerator_gui.png"));
final int x0=guiLeft, y0=this.guiTop, w=xSize, h=ySize; final int x0=leftPos, y0=this.topPos, w=imageWidth, h=imageHeight;
blit(mx, x0, y0, 0, 0, w, h); blit(mx, x0, y0, 0, 0, w, h);
RenderSystem.disableBlend(); RenderSystem.disableBlend();
} }

View file

@ -8,7 +8,7 @@
*/ */
package wile.engineersdecor.blocks; package wile.engineersdecor.blocks;
import net.minecraft.block.Block; import net.minecraft.block.AbstractBlock;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluids; import net.minecraft.fluid.Fluids;
@ -25,9 +25,10 @@ import javax.annotation.Nullable;
import java.util.Arrays; import java.util.Arrays;
public class EdWindowBlock extends DecorBlock.DirectedWaterLoggable implements IDecorBlock public class EdWindowBlock extends DecorBlock.DirectedWaterLoggable implements IDecorBlock
{ {
public EdWindowBlock(long config, Block.Properties builder, final AxisAlignedBB unrotatedAABB) public EdWindowBlock(long config, AbstractBlock.Properties builder, final AxisAlignedBB unrotatedAABB)
{ super(config, builder, unrotatedAABB); } { super(config, builder, unrotatedAABB); }
@Override @Override
@ -38,41 +39,41 @@ public class EdWindowBlock extends DecorBlock.DirectedWaterLoggable implements I
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
Direction facing = context.getPlacementHorizontalFacing(); Direction facing = context.getHorizontalDirection();
if(Math.abs(context.getPlayer().getLookVec().y) > 0.9) { if(Math.abs(context.getPlayer().getLookAngle().y) > 0.9) {
facing = context.getNearestLookingDirection(); facing = context.getNearestLookingDirection();
} else { } else {
for(Direction f: Direction.values()) { for(Direction f: Direction.values()) {
BlockState st = context.getWorld().getBlockState(context.getPos().offset(f)); BlockState st = context.getLevel().getBlockState(context.getClickedPos().relative(f));
if(st.getBlock() == this) { if(st.getBlock() == this) {
facing = st.get(FACING); facing = st.getValue(FACING);
break; break;
} }
} }
} }
return super.getStateForPlacement(context).with(FACING, facing); return super.getStateForPlacement(context).setValue(FACING, facing);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ {
if(player.getHeldItem(hand).getItem() != asItem()) return ActionResultType.PASS; if(player.getItemInHand(hand).getItem() != asItem()) return ActionResultType.PASS;
final Direction facing = state.get(FACING); final Direction facing = state.getValue(FACING);
if(facing.getAxis() != hit.getFace().getAxis()) return ActionResultType.PASS; if(facing.getAxis() != hit.getDirection().getAxis()) return ActionResultType.PASS;
Arrays.stream(Direction.getFacingDirections(player)) Arrays.stream(Direction.orderedByNearest(player))
.filter(d->d.getAxis() != facing.getAxis()) .filter(d->d.getAxis() != facing.getAxis())
.filter(d->world.getBlockState(pos.offset(d)).isReplaceable((new DirectionalPlaceContext(world, pos.offset(d), facing.getOpposite(), player.getHeldItem(hand), facing)))) .filter(d->world.getBlockState(pos.relative(d)).canBeReplaced((new DirectionalPlaceContext(world, pos.relative(d), facing.getOpposite(), player.getItemInHand(hand), facing))))
.findFirst().ifPresent((d)->{ .findFirst().ifPresent((d)->{
BlockState st = getDefaultState() BlockState st = defaultBlockState()
.with(FACING, facing) .setValue(FACING, facing)
.with(WATERLOGGED,world.getBlockState(pos.offset(d)).getFluidState().getFluid()==Fluids.WATER); .setValue(WATERLOGGED,world.getBlockState(pos.relative(d)).getFluidState().getType()==Fluids.WATER);
world.setBlockState(pos.offset(d), st, 1|2); world.setBlock(pos.relative(d), st, 1|2);
world.playSound(player, pos, SoundEvents.BLOCK_METAL_PLACE, SoundCategory.BLOCKS, 1f, 1f); world.playSound(player, pos, SoundEvents.METAL_PLACE, SoundCategory.BLOCKS, 1f, 1f);
player.getHeldItem(hand).shrink(1); player.getItemInHand(hand).shrink(1);
} }
); );
return ActionResultType.func_233537_a_(world.isRemote()); return ActionResultType.sidedSuccess(world.isClientSide());
} }
@Override @Override
@ -81,7 +82,7 @@ public class EdWindowBlock extends DecorBlock.DirectedWaterLoggable implements I
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean isTransparent(BlockState state) public boolean useShapeForLightOcclusion(BlockState state)
{ return true; } { return true; }
} }

View file

@ -52,13 +52,13 @@ public class ModRenderers
{ return Vector3d.ZERO; } { return Vector3d.ZERO; }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ResourceLocation getEntityTexture(T entity) public ResourceLocation getTextureLocation(T entity)
{ return AtlasTexture.LOCATION_BLOCKS_TEXTURE; } { return AtlasTexture.LOCATION_BLOCKS; }
protected boolean canRenderName(T entity) protected boolean shouldShowName(T entity)
{ return false; } { return false; }
protected void renderName(T entity, ITextComponent displayName, MatrixStack matrixStack, IRenderTypeBuffer buffer, int packedLight) protected void renderNameTag(T entity, ITextComponent displayName, MatrixStack matrixStack, IRenderTypeBuffer buffer, int packedLight)
{} {}
} }
@ -89,11 +89,11 @@ public class ModRenderers
{ {
if(tesr_error_counter <= 0) return; if(tesr_error_counter <= 0) return;
try { try {
final int di = MathHelper.clamp(te.getWorld().getBlockState(te.getPos()).get(CraftingTableBlock.HORIZONTAL_FACING).getHorizontalIndex(), 0, 3); final int di = MathHelper.clamp(te.getLevel().getBlockState(te.getBlockPos()).getValue(CraftingTableBlock.HORIZONTAL_FACING).get2DDataValue(), 0, 3);
long posrnd = te.getPos().toLong(); long posrnd = te.getBlockPos().asLong();
posrnd = (posrnd>>16)^(posrnd<<1); posrnd = (posrnd>>16)^(posrnd<<1);
for(int i=0; i<9; ++i) { for(int i=0; i<9; ++i) {
final ItemStack stack = te.mainInventory().getStackInSlot(i); final ItemStack stack = te.mainInventory().getItem(i);
if(stack.isEmpty()) continue; if(stack.isEmpty()) continue;
float prnd = ((float)(((Integer.rotateRight(stack.getItem().hashCode()^(int)posrnd,(stack.getCount()+i)&31)))&1023))/1024f; float prnd = ((float)(((Integer.rotateRight(stack.getItem().hashCode()^(int)posrnd,(stack.getCount()+i)&31)))&1023))/1024f;
float rndo = gap * ((prnd*0.1f)-0.05f); float rndo = gap * ((prnd*0.1f)-0.05f);
@ -101,14 +101,14 @@ public class ModRenderers
float oy = 0.5f; float oy = 0.5f;
float ry = ((yrotations[di]+180) + ((prnd*60)-30)) % 360; float ry = ((yrotations[di]+180) + ((prnd*60)-30)) % 360;
if(stack.isEmpty()) return; if(stack.isEmpty()) return;
mxs.push(); mxs.pushPose();
mxs.translate(0.5+ox, 0.5+oy, 0.5+oz); mxs.translate(0.5+ox, 0.5+oy, 0.5+oz);
mxs.rotate(Vector3f.XP.rotationDegrees(90.0f)); mxs.mulPose(Vector3f.XP.rotationDegrees(90.0f));
mxs.rotate(Vector3f.ZP.rotationDegrees(ry)); mxs.mulPose(Vector3f.ZP.rotationDegrees(ry));
mxs.translate(rndo, rndo, 0); mxs.translate(rndo, rndo, 0);
mxs.scale(scaler, scaler, scaler); mxs.scale(scaler, scaler, scaler);
Minecraft.getInstance().getItemRenderer().renderItem(stack, net.minecraft.client.renderer.model.ItemCameraTransforms.TransformType.FIXED, i5, i6, mxs, buf); Minecraft.getInstance().getItemRenderer().renderStatic(stack, net.minecraft.client.renderer.model.ItemCameraTransforms.TransformType.FIXED, i5, i6, mxs, buf);
mxs.pop(); mxs.popPose();
} }
} catch(Throwable e) { } catch(Throwable e) {
if(--tesr_error_counter<=0) { if(--tesr_error_counter<=0) {
@ -146,15 +146,15 @@ public class ModRenderers
try { try {
final ItemStack stack = te.getItemFrameStack(); final ItemStack stack = te.getItemFrameStack();
if(stack.isEmpty()) return; if(stack.isEmpty()) return;
final int di = MathHelper.clamp(te.getWorld().getBlockState(te.getPos()).get(EdLabeledCrate.LabeledCrateBlock.HORIZONTAL_FACING).getHorizontalIndex(), 0, 3); final int di = MathHelper.clamp(te.getLevel().getBlockState(te.getBlockPos()).getValue(EdLabeledCrate.LabeledCrateBlock.HORIZONTAL_FACING).get2DDataValue(), 0, 3);
double ox = tr[di][0], oy = tr[di][1], oz = tr[di][2]; double ox = tr[di][0], oy = tr[di][1], oz = tr[di][2];
float ry = (float)tr[di][3]; float ry = (float)tr[di][3];
mxs.push(); mxs.pushPose();
mxs.translate(0.5+ox, 0.5+oy, 0.5+oz); mxs.translate(0.5+ox, 0.5+oy, 0.5+oz);
mxs.rotate(Vector3f.YP.rotationDegrees(ry)); mxs.mulPose(Vector3f.YP.rotationDegrees(ry));
mxs.scale(scaler, scaler, scaler); mxs.scale(scaler, scaler, scaler);
Minecraft.getInstance().getItemRenderer().renderItem(stack, net.minecraft.client.renderer.model.ItemCameraTransforms.TransformType.FIXED, i5, i6, mxs, buf); Minecraft.getInstance().getItemRenderer().renderStatic(stack, net.minecraft.client.renderer.model.ItemCameraTransforms.TransformType.FIXED, i5, i6, mxs, buf);
mxs.pop(); mxs.popPose();
} catch(Throwable e) { } catch(Throwable e) {
if(--tesr_error_counter<=0) { if(--tesr_error_counter<=0) {
ModEngineersDecor.logger().error("TER was disabled (because broken), exception was: " + e.getMessage()); ModEngineersDecor.logger().error("TER was disabled (because broken), exception was: " + e.getMessage());

View file

@ -36,7 +36,7 @@ public class TreeCutting
); );
private static boolean isLog(BlockState state) private static boolean isLog(BlockState state)
{ return (state.getBlock().isIn(BlockTags.LOGS)) || (state.getBlock().getTags().contains(new ResourceLocation("minecraft","logs"))); } { return (state.getBlock().is(BlockTags.LOGS)) || (state.getBlock().getTags().contains(new ResourceLocation("minecraft","logs"))); }
private static boolean isSameLog(BlockState a, BlockState b) private static boolean isSameLog(BlockState a, BlockState b)
{ return (a.getBlock()==b.getBlock()); } { return (a.getBlock()==b.getBlock()); }
@ -52,9 +52,9 @@ public class TreeCutting
{ {
ArrayList<BlockPos> to_decay = new ArrayList<BlockPos>(); ArrayList<BlockPos> to_decay = new ArrayList<BlockPos>();
for(int y=-1; y<=1; ++y) { for(int y=-1; y<=1; ++y) {
final BlockPos layer = centerPos.add(0,y,0); final BlockPos layer = centerPos.offset(0,y,0);
for(Vector3i v:hoffsets) { for(Vector3i v:hoffsets) {
BlockPos pos = layer.add(v); BlockPos pos = layer.offset(v);
if((!checked.contains(pos)) && (world.getBlockState(pos).getBlock()==leaf_type_state.getBlock())) { if((!checked.contains(pos)) && (world.getBlockState(pos).getBlock()==leaf_type_state.getBlock())) {
checked.add(pos); checked.add(pos);
to_decay.add(pos); to_decay.add(pos);
@ -69,13 +69,13 @@ public class TreeCutting
private static void breakBlock(World world, BlockPos pos) private static void breakBlock(World world, BlockPos pos)
{ {
Block.spawnDrops(world.getBlockState(pos), world, pos); Block.dropResources(world.getBlockState(pos), world, pos);
world.setBlockState(pos, world.getFluidState(pos).getBlockState(), 1|2|8); world.setBlock(pos, world.getFluidState(pos).createLegacyBlock(), 1|2|8);
} }
public static int chopTree(World world, BlockState broken_state, BlockPos startPos, int max_blocks_to_break, boolean without_target_block) public static int chopTree(World world, BlockState broken_state, BlockPos startPos, int max_blocks_to_break, boolean without_target_block)
{ {
if(world.isRemote || !isLog(broken_state)) return 0; if(world.isClientSide || !isLog(broken_state)) return 0;
final long ymin = startPos.getY(); final long ymin = startPos.getY();
final long max_leaf_distance = 8; final long max_leaf_distance = 8;
Set<BlockPos> checked = new HashSet<BlockPos>(); Set<BlockPos> checked = new HashSet<BlockPos>();
@ -93,7 +93,7 @@ public class TreeCutting
while(!queue.isEmpty() && (--steps_left >= 0)) { while(!queue.isEmpty() && (--steps_left >= 0)) {
final BlockPos pos = queue.removeFirst(); final BlockPos pos = queue.removeFirst();
// Vertical search // Vertical search
final BlockPos uppos = pos.up(); final BlockPos uppos = pos.above();
final BlockState upstate = world.getBlockState(uppos); final BlockState upstate = world.getBlockState(uppos);
if(!checked.contains(uppos)) { if(!checked.contains(uppos)) {
checked.add(uppos); checked.add(uppos);
@ -104,11 +104,11 @@ public class TreeCutting
steps_left = 128; steps_left = 128;
} else { } else {
boolean isleaf = isLeaves(upstate); boolean isleaf = isLeaves(upstate);
if(isleaf || world.isAirBlock(uppos) || (upstate.getBlock() instanceof VineBlock)) { if(isleaf || world.isEmptyBlock(uppos) || (upstate.getBlock() instanceof VineBlock)) {
if(isleaf) to_decay.add(uppos); if(isleaf) to_decay.add(uppos);
// Up is air, check adjacent for diagonal up (e.g. Accacia) // Up is air, check adjacent for diagonal up (e.g. Accacia)
for(Vector3i v:hoffsets) { for(Vector3i v:hoffsets) {
final BlockPos p = uppos.add(v); final BlockPos p = uppos.offset(v);
if(checked.contains(p)) continue; if(checked.contains(p)) continue;
checked.add(p); checked.add(p);
final BlockState st = world.getBlockState(p); final BlockState st = world.getBlockState(p);
@ -125,10 +125,10 @@ public class TreeCutting
} }
// Lateral search // Lateral search
for(Vector3i v:hoffsets) { for(Vector3i v:hoffsets) {
final BlockPos p = pos.add(v); final BlockPos p = pos.offset(v);
if(checked.contains(p)) continue; if(checked.contains(p)) continue;
checked.add(p); checked.add(p);
if(p.distanceSq(new BlockPos(startPos.getX(), p.getY(), startPos.getZ())) > (cutlevel > 2 ? 256 : 9)) continue; if(p.distSqr(new BlockPos(startPos.getX(), p.getY(), startPos.getZ())) > (cutlevel > 2 ? 256 : 9)) continue;
final BlockState st = world.getBlockState(p); final BlockState st = world.getBlockState(p);
final Block bl = st.getBlock(); final Block bl = st.getBlock();
if(isSameLog(st, broken_state)) { if(isSameLog(st, broken_state)) {

View file

@ -43,7 +43,7 @@ public class JEIPlugin implements mezz.jei.api.IModPlugin
if(!ModConfig.isOptedOut(ModContent.CRAFTING_TABLE)) { if(!ModConfig.isOptedOut(ModContent.CRAFTING_TABLE)) {
try { try {
registration.addRecipeTransferHandler( registration.addRecipeTransferHandler(
EdCraftingTable.CraftingTableContainer.class, EdCraftingTable.CraftingTableUiContainer.class,
VanillaRecipeCategoryUid.CRAFTING, VanillaRecipeCategoryUid.CRAFTING,
1, 9, 10, 36+CraftingTableTileEntity.NUM_OF_STORAGE_SLOTS 1, 9, 10, 36+CraftingTableTileEntity.NUM_OF_STORAGE_SLOTS
); );

View file

@ -32,11 +32,11 @@ public class EdItem extends Item
public static final Collection<ItemGroup> DISABLED_TABS = new ArrayList<ItemGroup>(); public static final Collection<ItemGroup> DISABLED_TABS = new ArrayList<ItemGroup>();
public EdItem(Item.Properties properties) public EdItem(Item.Properties properties)
{ super(properties.group(ModEngineersDecor.ITEMGROUP)); } { super(properties.tab(ModEngineersDecor.ITEMGROUP)); }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); } { Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); }
@Override @Override

View file

@ -41,6 +41,8 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import wile.engineersdecor.libmc.blocks.StandardBlocks.IStandardBlock.RenderTypeHint;
public class SlabSliceBlock extends StandardBlocks.WaterLoggable implements StandardBlocks.IStandardBlock public class SlabSliceBlock extends StandardBlocks.WaterLoggable implements StandardBlocks.IStandardBlock
{ {
public static final IntegerProperty PARTS = IntegerProperty.create("parts", 0, 14); public static final IntegerProperty PARTS = IntegerProperty.create("parts", 0, 14);
@ -70,15 +72,15 @@ public class SlabSliceBlock extends StandardBlocks.WaterLoggable implements Stan
public static void on_config(boolean direct_slab_pickup) public static void on_config(boolean direct_slab_pickup)
{ with_pickup = direct_slab_pickup; } { with_pickup = direct_slab_pickup; }
public SlabSliceBlock(long config, Block.Properties builder) public SlabSliceBlock(long config, AbstractBlock.Properties builder)
{ super(config, builder); } { super(config, builder); }
protected boolean is_cube(BlockState state) protected boolean is_cube(BlockState state)
{ return state.get(PARTS) == 0x07; } { return state.getValue(PARTS) == 0x07; }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ {
if(!Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true)) return; if(!Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true)) return;
if(with_pickup) Auxiliaries.Tooltip.addInformation("engineersdecor.tooltip.slabpickup", tooltip); if(with_pickup) Auxiliaries.Tooltip.addInformation("engineersdecor.tooltip.slabpickup", tooltip);
@ -89,7 +91,7 @@ public class SlabSliceBlock extends StandardBlocks.WaterLoggable implements Stan
{ return (((config & StandardBlocks.CFG_TRANSLUCENT)!=0) ? (RenderTypeHint.TRANSLUCENT) : (RenderTypeHint.CUTOUT)); } { return (((config & StandardBlocks.CFG_TRANSLUCENT)!=0) ? (RenderTypeHint.TRANSLUCENT) : (RenderTypeHint.CUTOUT)); }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@ -98,52 +100,52 @@ public class SlabSliceBlock extends StandardBlocks.WaterLoggable implements Stan
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext)
{ return AABBs[state.get(PARTS) & 0xf]; } { return AABBs[state.getValue(PARTS) & 0xf]; }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return getShape(state, world, pos, selectionContext); } { return getShape(state, world, pos, selectionContext); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(PARTS); } { super.createBlockStateDefinition(builder); builder.add(PARTS); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
final BlockPos pos = context.getPos(); final BlockPos pos = context.getClickedPos();
BlockState state = context.getWorld().getBlockState(pos); BlockState state = context.getLevel().getBlockState(pos);
if(state.getBlock() == this) { if(state.getBlock() == this) {
int parts = state.get(PARTS); int parts = state.getValue(PARTS);
if(parts == 7) return null; // -> is already a full block. if(parts == 7) return null; // -> is already a full block.
parts += (parts < 7) ? 1 : -1; parts += (parts < 7) ? 1 : -1;
if(parts==7) state = state.with(WATERLOGGED, false); if(parts==7) state = state.setValue(WATERLOGGED, false);
return state.with(PARTS, parts); return state.setValue(PARTS, parts);
} else { } else {
final Direction face = context.getFace(); final Direction face = context.getClickedFace();
final BlockState placement_state = super.getStateForPlacement(context); // fluid state final BlockState placement_state = super.getStateForPlacement(context); // fluid state
if(face == Direction.UP) return placement_state.with(PARTS, 0); if(face == Direction.UP) return placement_state.setValue(PARTS, 0);
if(face == Direction.DOWN) return placement_state.with(PARTS, 14); if(face == Direction.DOWN) return placement_state.setValue(PARTS, 14);
if(!face.getAxis().isHorizontal()) return placement_state; if(!face.getAxis().isHorizontal()) return placement_state;
final boolean isupper = ((context.getHitVec().getY() - context.getPos().getY()) > 0.5); final boolean isupper = ((context.getClickLocation().y() - context.getClickedPos().getY()) > 0.5);
return placement_state.with(PARTS, isupper ? 14 : 0); return placement_state.setValue(PARTS, isupper ? 14 : 0);
} }
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean isReplaceable(BlockState state, BlockItemUseContext context) public boolean canBeReplaced(BlockState state, BlockItemUseContext context)
{ {
if(context.getItem().getItem() != this.asItem()) return false; if(context.getItemInHand().getItem() != this.asItem()) return false;
if(!context.replacingClickedOnBlock()) return true; if(!context.replacingClickedOnBlock()) return true;
final Direction face = context.getFace(); final Direction face = context.getClickedFace();
final int parts = state.get(PARTS); final int parts = state.getValue(PARTS);
if(parts == 7) return false; if(parts == 7) return false;
if((face == Direction.UP) && (parts < 7)) return true; if((face == Direction.UP) && (parts < 7)) return true;
if((face == Direction.DOWN) && (parts > 7)) return true; if((face == Direction.DOWN) && (parts > 7)) return true;
if(!face.getAxis().isHorizontal()) return false; if(!face.getAxis().isHorizontal()) return false;
final boolean isupper = ((context.getHitVec().getY() - context.getPos().getY()) > 0.5); final boolean isupper = ((context.getClickLocation().y() - context.getClickedPos().getY()) > 0.5);
return isupper ? (parts==0) : (parts==1); return isupper ? (parts==0) : (parts==1);
} }
@ -163,30 +165,30 @@ public class SlabSliceBlock extends StandardBlocks.WaterLoggable implements Stan
@Override @Override
public List<ItemStack> dropList(BlockState state, World world, TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, TileEntity te, boolean explosion)
{ return new ArrayList<ItemStack>(Collections.singletonList(new ItemStack(this.asItem(), num_slabs_contained_in_parts_[state.get(PARTS) & 0xf]))); } { return new ArrayList<ItemStack>(Collections.singletonList(new ItemStack(this.asItem(), num_slabs_contained_in_parts_[state.getValue(PARTS) & 0xf]))); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void onBlockClicked(BlockState state, World world, BlockPos pos, PlayerEntity player) public void attack(BlockState state, World world, BlockPos pos, PlayerEntity player)
{ {
if((world.isRemote) || (!with_pickup)) return; if((world.isClientSide) || (!with_pickup)) return;
final ItemStack stack = player.getHeldItemMainhand(); final ItemStack stack = player.getMainHandItem();
if(stack.isEmpty() || (Block.getBlockFromItem(stack.getItem()) != this)) return; if(stack.isEmpty() || (Block.byItem(stack.getItem()) != this)) return;
if(stack.getCount() >= stack.getMaxStackSize()) return; if(stack.getCount() >= stack.getMaxStackSize()) return;
Vector3d lv = player.getLookVec(); Vector3d lv = player.getLookAngle();
Direction facing = Direction.getFacingFromVector((float)lv.x, (float)lv.y, (float)lv.z); Direction facing = Direction.getNearest((float)lv.x, (float)lv.y, (float)lv.z);
if((facing != Direction.UP) && (facing != Direction.DOWN)) return; if((facing != Direction.UP) && (facing != Direction.DOWN)) return;
if(state.getBlock() != this) return; if(state.getBlock() != this) return;
int parts = state.get(PARTS); int parts = state.getValue(PARTS);
if((facing == Direction.DOWN) && (parts <= 7)) { if((facing == Direction.DOWN) && (parts <= 7)) {
if(parts > 0) { if(parts > 0) {
world.setBlockState(pos, state.with(PARTS, parts-1), 3); world.setBlock(pos, state.setValue(PARTS, parts-1), 3);
} else { } else {
world.removeBlock(pos, false); world.removeBlock(pos, false);
} }
} else if((facing == Direction.UP) && (parts >= 7)) { } else if((facing == Direction.UP) && (parts >= 7)) {
if(parts < 14) { if(parts < 14) {
world.setBlockState(pos, state.with(PARTS, parts + 1), 3); world.setBlock(pos, state.setValue(PARTS, parts + 1), 3);
} else { } else {
world.removeBlock(pos, false); world.removeBlock(pos, false);
} }
@ -195,18 +197,18 @@ public class SlabSliceBlock extends StandardBlocks.WaterLoggable implements Stan
} }
if(!player.isCreative()) { if(!player.isCreative()) {
stack.grow(1); stack.grow(1);
if(player.inventory != null) player.inventory.markDirty(); // @todo: check if inventory can actually be null if(player.inventory != null) player.inventory.setChanged(); // @todo: check if inventory can actually be null
} }
SoundType st = this.getSoundType(state, world, pos, null); SoundType st = this.getSoundType(state, world, pos, null);
world.playSound(player, pos, st.getPlaceSound(), SoundCategory.BLOCKS, (st.getVolume()+1f)/2.5f, 0.9f*st.getPitch()); world.playSound(player, pos, st.getPlaceSound(), SoundCategory.BLOCKS, (st.getVolume()+1f)/2.5f, 0.9f*st.getPitch());
} }
@Override @Override
public boolean receiveFluid(IWorld world, BlockPos pos, BlockState state, FluidState fluidState) public boolean placeLiquid(IWorld world, BlockPos pos, BlockState state, FluidState fluidState)
{ return (state.get(PARTS)==14) ? false : super.receiveFluid(world, pos, state, fluidState); } { return (state.getValue(PARTS)==14) ? false : super.placeLiquid(world, pos, state, fluidState); }
@Override @Override
public boolean canContainFluid(IBlockReader world, BlockPos pos, BlockState state, Fluid fluid) public boolean canPlaceLiquid(IBlockReader world, BlockPos pos, BlockState state, Fluid fluid)
{ return (state.get(PARTS)==14) ? false : super.canContainFluid(world, pos, state, fluid); } { return (state.getValue(PARTS)==14) ? false : super.canPlaceLiquid(world, pos, state, fluid); }
} }

View file

@ -76,7 +76,7 @@ public class StandardBlocks
{ return false; } { return false; }
default List<ItemStack> dropList(BlockState state, World world, @Nullable TileEntity te, boolean explosion) default List<ItemStack> dropList(BlockState state, World world, @Nullable TileEntity te, boolean explosion)
{ return Collections.singletonList((!world.isRemote()) ? (new ItemStack(state.getBlock().asItem())) : (ItemStack.EMPTY)); } { return Collections.singletonList((!world.isClientSide()) ? (new ItemStack(state.getBlock().asItem())) : (ItemStack.EMPTY)); }
enum RenderTypeHint { SOLID,CUTOUT,CUTOUT_MIPPED,TRANSLUCENT,TRANSLUCENT_NO_CRUMBLING } enum RenderTypeHint { SOLID,CUTOUT,CUTOUT_MIPPED,TRANSLUCENT,TRANSLUCENT_NO_CRUMBLING }
@ -102,12 +102,12 @@ public class StandardBlocks
{ {
public final long config; public final long config;
public BaseBlock(long conf, Block.Properties properties) public BaseBlock(long conf, AbstractBlock.Properties properties)
{ {
super(properties); super(properties);
config = conf; config = conf;
BlockState state = getStateContainer().getBaseState(); BlockState state = getStateDefinition().any();
setDefaultState(state); registerDefaultState(state);
} }
@Override @Override
@ -116,7 +116,7 @@ public class StandardBlocks
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); } { Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); }
@Override @Override
@ -125,16 +125,16 @@ public class StandardBlocks
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean allowsMovement(BlockState state, IBlockReader world, BlockPos pos, PathType type) public boolean isPathfindable(BlockState state, IBlockReader world, BlockPos pos, PathType type)
{ return ((config & CFG_AI_PASSABLE)==0) ? false : super.allowsMovement(state, world, pos, type); } { return ((config & CFG_AI_PASSABLE)==0) ? false : super.isPathfindable(state, world, pos, type); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void onReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean isMoving) public void onRemove(BlockState state, World world, BlockPos pos, BlockState newState, boolean isMoving)
{ {
if(state.hasTileEntity() && (state.getBlock() != newState.getBlock())) { if(state.hasTileEntity() && (state.getBlock() != newState.getBlock())) {
world.removeTileEntity(pos); world.removeBlockEntity(pos);
world.updateComparatorOutputLevel(pos, this); world.updateNeighbourForOutputSignal(pos, this);
} }
} }
@ -142,9 +142,9 @@ public class StandardBlocks
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder)
{ {
final ServerWorld world = builder.getWorld(); final ServerWorld world = builder.getLevel();
final Float explosion_radius = builder.get(LootParameters.EXPLOSION_RADIUS); final Float explosion_radius = builder.getOptionalParameter(LootParameters.EXPLOSION_RADIUS);
final TileEntity te = builder.get(LootParameters.BLOCK_ENTITY); final TileEntity te = builder.getOptionalParameter(LootParameters.BLOCK_ENTITY);
if((!hasDynamicDropList()) || (world==null)) return super.getDrops(state, builder); if((!hasDynamicDropList()) || (world==null)) return super.getDrops(state, builder);
boolean is_explosion = (explosion_radius!=null) && (explosion_radius > 0); boolean is_explosion = (explosion_radius!=null) && (explosion_radius > 0);
return dropList(state, world, te, is_explosion); return dropList(state, world, te, is_explosion);
@ -156,22 +156,22 @@ public class StandardBlocks
public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
private final VoxelShape vshape; private final VoxelShape vshape;
public Cutout(long conf, Block.Properties properties) public Cutout(long conf, AbstractBlock.Properties properties)
{ this(conf, properties, Auxiliaries.getPixeledAABB(0, 0, 0, 16, 16,16 )); } { this(conf, properties, Auxiliaries.getPixeledAABB(0, 0, 0, 16, 16,16 )); }
public Cutout(long conf, Block.Properties properties, AxisAlignedBB aabb) public Cutout(long conf, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ this(conf, properties, VoxelShapes.create(aabb)); } { this(conf, properties, VoxelShapes.create(aabb)); }
public Cutout(long conf, Block.Properties properties, AxisAlignedBB[] aabbs) public Cutout(long conf, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ this(conf, properties, Arrays.stream(aabbs).map(aabb->VoxelShapes.create(aabb)).reduce(VoxelShapes.empty(), (shape, aabb)->VoxelShapes.combine(shape, aabb, IBooleanFunction.OR))); } { this(conf, properties, Arrays.stream(aabbs).map(aabb->VoxelShapes.create(aabb)).reduce(VoxelShapes.empty(), (shape, aabb)->VoxelShapes.joinUnoptimized(shape, aabb, IBooleanFunction.OR))); }
public Cutout(long conf, Block.Properties properties, VoxelShape voxel_shape) public Cutout(long conf, AbstractBlock.Properties properties, VoxelShape voxel_shape)
{ {
super(conf, properties); super(conf, properties);
vshape = voxel_shape; vshape = voxel_shape;
BlockState state = getStateContainer().getBaseState(); BlockState state = getStateDefinition().any();
if((conf & CFG_WATERLOGGABLE)!=0) state = state.with(WATERLOGGED, false); if((conf & CFG_WATERLOGGABLE)!=0) state = state.setValue(WATERLOGGED, false);
setDefaultState(state); registerDefaultState(state);
} }
@Override @Override
@ -190,26 +190,26 @@ public class StandardBlocks
{ {
BlockState state = super.getStateForPlacement(context); BlockState state = super.getStateForPlacement(context);
if((config & CFG_WATERLOGGABLE)!=0) { if((config & CFG_WATERLOGGABLE)!=0) {
FluidState fs = context.getWorld().getFluidState(context.getPos()); FluidState fs = context.getLevel().getFluidState(context.getClickedPos());
state = state.with(WATERLOGGED,fs.getFluid()==Fluids.WATER); state = state.setValue(WATERLOGGED,fs.getType()==Fluids.WATER);
} }
return state; return state;
} }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public PushReaction getPushReaction(BlockState state) public PushReaction getPistonPushReaction(BlockState state)
{ return PushReaction.NORMAL; } { return PushReaction.NORMAL; }
@Override @Override
public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos) public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos)
{ {
if((config & CFG_WATERLOGGABLE)!=0) { if((config & CFG_WATERLOGGABLE)!=0) {
if(state.get(WATERLOGGED)) return false; if(state.getValue(WATERLOGGED)) return false;
} }
return super.propagatesSkylightDown(state, reader, pos); return super.propagatesSkylightDown(state, reader, pos);
} }
@ -219,17 +219,17 @@ public class StandardBlocks
public FluidState getFluidState(BlockState state) public FluidState getFluidState(BlockState state)
{ {
if((config & CFG_WATERLOGGABLE)!=0) { if((config & CFG_WATERLOGGABLE)!=0) {
return state.get(WATERLOGGED) ? Fluids.WATER.getStillFluidState(false) : super.getFluidState(state); return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state);
} }
return super.getFluidState(state); return super.getFluidState(state);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState updatePostPlacement(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos) public BlockState updateShape(BlockState state, Direction facing, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos)
{ {
if((config & CFG_WATERLOGGABLE)!=0) { if((config & CFG_WATERLOGGABLE)!=0) {
if(state.get(WATERLOGGED)) world.getPendingFluidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickRate(world)); if(state.getValue(WATERLOGGED)) world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world));
} }
return state; return state;
} }
@ -237,21 +237,21 @@ public class StandardBlocks
public static class WaterLoggable extends Cutout implements IWaterLoggable, IStandardBlock public static class WaterLoggable extends Cutout implements IWaterLoggable, IStandardBlock
{ {
public WaterLoggable(long config, Block.Properties properties) public WaterLoggable(long config, AbstractBlock.Properties properties)
{ super(config|CFG_WATERLOGGABLE, properties); } { super(config|CFG_WATERLOGGABLE, properties); }
public WaterLoggable(long config, Block.Properties properties, AxisAlignedBB aabb) public WaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ super(config|CFG_WATERLOGGABLE, properties, aabb); } { super(config|CFG_WATERLOGGABLE, properties, aabb); }
public WaterLoggable(long config, Block.Properties properties, VoxelShape voxel_shape) public WaterLoggable(long config, AbstractBlock.Properties properties, VoxelShape voxel_shape)
{ super(config|CFG_WATERLOGGABLE, properties, voxel_shape); } { super(config|CFG_WATERLOGGABLE, properties, voxel_shape); }
public WaterLoggable(long config, Block.Properties properties, AxisAlignedBB[] aabbs) public WaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ super(config|CFG_WATERLOGGABLE, properties, aabbs); } { super(config|CFG_WATERLOGGABLE, properties, aabbs); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(WATERLOGGED); } { super.createBlockStateDefinition(builder); builder.add(WATERLOGGED); }
} }
public static class Directed extends Cutout implements IStandardBlock public static class Directed extends Cutout implements IStandardBlock
@ -259,14 +259,14 @@ public class StandardBlocks
public static final DirectionProperty FACING = DirectionalBlock.FACING; public static final DirectionProperty FACING = DirectionalBlock.FACING;
protected final ArrayList<VoxelShape> vshapes; protected final ArrayList<VoxelShape> vshapes;
public Directed(long config, Block.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier) public Directed(long config, AbstractBlock.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ {
super(config, properties); super(config, properties);
setDefaultState(super.getDefaultState().with(FACING, Direction.UP)); registerDefaultState(super.defaultBlockState().setValue(FACING, Direction.UP));
vshapes = shape_supplier.get(); vshapes = shape_supplier.get();
} }
public Directed(long config, Block.Properties properties, final AxisAlignedBB[] unrotatedAABBs) public Directed(long config, AbstractBlock.Properties properties, final AxisAlignedBB[] unrotatedAABBs)
{ {
this(config, properties, ()->{ this(config, properties, ()->{
final boolean is_horizontal = ((config & CFG_HORIZIONTAL)!=0); final boolean is_horizontal = ((config & CFG_HORIZIONTAL)!=0);
@ -277,17 +277,17 @@ public class StandardBlocks
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.SOUTH, is_horizontal)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.SOUTH, is_horizontal)),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.WEST, is_horizontal)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.WEST, is_horizontal)),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.EAST, is_horizontal)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.EAST, is_horizontal)),
VoxelShapes.fullCube(), VoxelShapes.block(),
VoxelShapes.fullCube() VoxelShapes.block()
)); ));
}); });
} }
public Directed(long config, Block.Properties properties, final AxisAlignedBB unrotatedAABB) public Directed(long config, AbstractBlock.Properties properties, final AxisAlignedBB unrotatedAABB)
{ this(config, properties, new AxisAlignedBB[]{unrotatedAABB}); } { this(config, properties, new AxisAlignedBB[]{unrotatedAABB}); }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@ -296,24 +296,24 @@ public class StandardBlocks
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext)
{ return vshapes.get((state.get(FACING)).getIndex() & 0x7); } { return vshapes.get((state.getValue(FACING)).get3DDataValue() & 0x7); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return getShape(state, world, pos, selectionContext); } { return getShape(state, world, pos, selectionContext); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(FACING); } { super.createBlockStateDefinition(builder); builder.add(FACING); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
Direction facing = context.getFace(); Direction facing = context.getClickedFace();
if((config & (CFG_HORIZIONTAL|CFG_LOOK_PLACEMENT)) == (CFG_HORIZIONTAL|CFG_LOOK_PLACEMENT)) { if((config & (CFG_HORIZIONTAL|CFG_LOOK_PLACEMENT)) == (CFG_HORIZIONTAL|CFG_LOOK_PLACEMENT)) {
// horizontal placement in direction the player is looking // horizontal placement in direction the player is looking
facing = context.getPlacementHorizontalFacing(); facing = context.getHorizontalDirection();
} else if((config & (CFG_HORIZIONTAL|CFG_LOOK_PLACEMENT)) == (CFG_HORIZIONTAL)) { } else if((config & (CFG_HORIZIONTAL|CFG_LOOK_PLACEMENT)) == (CFG_HORIZIONTAL)) {
// horizontal placement on a face // horizontal placement on a face
if(((facing==Direction.UP)||(facing==Direction.DOWN))) return null; if(((facing==Direction.UP)||(facing==Direction.DOWN))) return null;
@ -324,113 +324,113 @@ public class StandardBlocks
// default: placement on the face the player clicking // default: placement on the face the player clicking
} }
if((config & CFG_OPPOSITE_PLACEMENT)!=0) facing = facing.getOpposite(); if((config & CFG_OPPOSITE_PLACEMENT)!=0) facing = facing.getOpposite();
if(((config & CFG_FLIP_PLACEMENT_SHIFTCLICK) != 0) && (context.getPlayer().isSneaking())) facing = facing.getOpposite(); if(((config & CFG_FLIP_PLACEMENT_SHIFTCLICK) != 0) && (context.getPlayer().isShiftKeyDown())) facing = facing.getOpposite();
return super.getStateForPlacement(context).with(FACING, facing); return super.getStateForPlacement(context).setValue(FACING, facing);
} }
} }
public static class Horizontal extends Cutout implements IStandardBlock public static class Horizontal extends Cutout implements IStandardBlock
{ {
public static final DirectionProperty HORIZONTAL_FACING = HorizontalBlock.HORIZONTAL_FACING; public static final DirectionProperty HORIZONTAL_FACING = HorizontalBlock.FACING;
protected final ArrayList<VoxelShape> vshapes; protected final ArrayList<VoxelShape> vshapes;
public Horizontal(long config, Block.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier) public Horizontal(long config, AbstractBlock.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ {
super(config|CFG_HORIZIONTAL, properties); super(config|CFG_HORIZIONTAL, properties);
setDefaultState(super.getDefaultState().with(HORIZONTAL_FACING, Direction.NORTH)); registerDefaultState(super.defaultBlockState().setValue(HORIZONTAL_FACING, Direction.NORTH));
vshapes = shape_supplier.get(); vshapes = shape_supplier.get();
} }
public Horizontal(long config, Block.Properties properties, final AxisAlignedBB[] unrotatedAABBs) public Horizontal(long config, AbstractBlock.Properties properties, final AxisAlignedBB[] unrotatedAABBs)
{ this(config, properties, ()->makeHorizontalShapeLookup(unrotatedAABBs)); } { this(config, properties, ()->makeHorizontalShapeLookup(unrotatedAABBs)); }
public Horizontal(long config, Block.Properties properties, final AxisAlignedBB unrotatedAABB) public Horizontal(long config, AbstractBlock.Properties properties, final AxisAlignedBB unrotatedAABB)
{ this(config, properties, new AxisAlignedBB[]{unrotatedAABB}); } { this(config, properties, new AxisAlignedBB[]{unrotatedAABB}); }
protected static ArrayList<VoxelShape> makeHorizontalShapeLookup(final AxisAlignedBB[] unrotatedAABBs) protected static ArrayList<VoxelShape> makeHorizontalShapeLookup(final AxisAlignedBB[] unrotatedAABBs)
{ {
return new ArrayList<VoxelShape>(Arrays.asList( return new ArrayList<VoxelShape>(Arrays.asList(
VoxelShapes.fullCube(), VoxelShapes.block(),
VoxelShapes.fullCube(), VoxelShapes.block(),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.NORTH, true)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.NORTH, true)),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.SOUTH, true)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.SOUTH, true)),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.WEST, true)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.WEST, true)),
Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.EAST, true)), Auxiliaries.getUnionShape(Auxiliaries.getRotatedAABB(unrotatedAABBs, Direction.EAST, true)),
VoxelShapes.fullCube(), VoxelShapes.block(),
VoxelShapes.fullCube() VoxelShapes.block()
)); ));
} }
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext)
{ return vshapes.get((state.get(HORIZONTAL_FACING)).getIndex() & 0x7); } { return vshapes.get((state.getValue(HORIZONTAL_FACING)).get3DDataValue() & 0x7); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return getShape(state, world, pos, selectionContext); } { return getShape(state, world, pos, selectionContext); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(HORIZONTAL_FACING); } { super.createBlockStateDefinition(builder); builder.add(HORIZONTAL_FACING); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
Direction facing = context.getFace(); Direction facing = context.getClickedFace();
if((config & CFG_LOOK_PLACEMENT) != 0) { if((config & CFG_LOOK_PLACEMENT) != 0) {
// horizontal placement in direction the player is looking // horizontal placement in direction the player is looking
facing = context.getPlacementHorizontalFacing(); facing = context.getHorizontalDirection();
} else { } else {
// horizontal placement on a face // horizontal placement on a face
facing = ((facing==Direction.UP)||(facing==Direction.DOWN)) ? (context.getPlacementHorizontalFacing()) : facing; facing = ((facing==Direction.UP)||(facing==Direction.DOWN)) ? (context.getHorizontalDirection()) : facing;
} }
if((config & CFG_OPPOSITE_PLACEMENT)!=0) facing = facing.getOpposite(); if((config & CFG_OPPOSITE_PLACEMENT)!=0) facing = facing.getOpposite();
if(((config & CFG_FLIP_PLACEMENT_SHIFTCLICK) != 0) && (context.getPlayer().isSneaking())) facing = facing.getOpposite(); if(((config & CFG_FLIP_PLACEMENT_SHIFTCLICK) != 0) && (context.getPlayer().isShiftKeyDown())) facing = facing.getOpposite();
return super.getStateForPlacement(context).with(HORIZONTAL_FACING, facing); return super.getStateForPlacement(context).setValue(HORIZONTAL_FACING, facing);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState rotate(BlockState state, Rotation rot) public BlockState rotate(BlockState state, Rotation rot)
{ return state.with(HORIZONTAL_FACING, rot.rotate(state.get(HORIZONTAL_FACING))); } { return state.setValue(HORIZONTAL_FACING, rot.rotate(state.getValue(HORIZONTAL_FACING))); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState mirror(BlockState state, Mirror mirrorIn) public BlockState mirror(BlockState state, Mirror mirrorIn)
{ return state.rotate(mirrorIn.toRotation(state.get(HORIZONTAL_FACING))); } { return state.rotate(mirrorIn.getRotation(state.getValue(HORIZONTAL_FACING))); }
} }
public static class DirectedWaterLoggable extends Directed implements IWaterLoggable, IStandardBlock public static class DirectedWaterLoggable extends Directed implements IWaterLoggable, IStandardBlock
{ {
public DirectedWaterLoggable(long config, Block.Properties properties, AxisAlignedBB aabb) public DirectedWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ super(config|CFG_WATERLOGGABLE, properties, aabb); } { super(config|CFG_WATERLOGGABLE, properties, aabb); }
public DirectedWaterLoggable(long config, Block.Properties properties, AxisAlignedBB[] aabbs) public DirectedWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ super(config|CFG_WATERLOGGABLE, properties, aabbs); } { super(config|CFG_WATERLOGGABLE, properties, aabbs); }
public DirectedWaterLoggable(long config, Block.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier) public DirectedWaterLoggable(long config, AbstractBlock.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ super(config|CFG_WATERLOGGABLE, properties, shape_supplier); } { super(config|CFG_WATERLOGGABLE, properties, shape_supplier); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(WATERLOGGED); } { super.createBlockStateDefinition(builder); builder.add(WATERLOGGED); }
} }
public static class HorizontalWaterLoggable extends Horizontal implements IWaterLoggable, IStandardBlock public static class HorizontalWaterLoggable extends Horizontal implements IWaterLoggable, IStandardBlock
{ {
public HorizontalWaterLoggable(long config, Block.Properties properties, AxisAlignedBB aabb) public HorizontalWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB aabb)
{ super(config|CFG_WATERLOGGABLE|CFG_HORIZIONTAL, properties, aabb); } { super(config|CFG_WATERLOGGABLE|CFG_HORIZIONTAL, properties, aabb); }
public HorizontalWaterLoggable(long config, Block.Properties properties, AxisAlignedBB[] aabbs) public HorizontalWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB[] aabbs)
{ super(config|CFG_WATERLOGGABLE|CFG_HORIZIONTAL, properties, aabbs); } { super(config|CFG_WATERLOGGABLE|CFG_HORIZIONTAL, properties, aabbs); }
public HorizontalWaterLoggable(long config, Block.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier) public HorizontalWaterLoggable(long config, AbstractBlock.Properties properties, final Supplier<ArrayList<VoxelShape>> shape_supplier)
{ super(config|CFG_WATERLOGGABLE|CFG_HORIZIONTAL, properties, shape_supplier); } { super(config|CFG_WATERLOGGABLE|CFG_HORIZIONTAL, properties, shape_supplier); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(WATERLOGGED); } { super.createBlockStateDefinition(builder); builder.add(WATERLOGGED); }
} }
static public class HorizontalFourWayWaterLoggable extends WaterLoggable implements IStandardBlock static public class HorizontalFourWayWaterLoggable extends WaterLoggable implements IStandardBlock
@ -442,55 +442,55 @@ public class StandardBlocks
protected final Map<BlockState, VoxelShape> shapes; protected final Map<BlockState, VoxelShape> shapes;
protected final Map<BlockState, VoxelShape> collision_shapes; protected final Map<BlockState, VoxelShape> collision_shapes;
public HorizontalFourWayWaterLoggable(long config, Block.Properties properties, AxisAlignedBB base_aabb, final AxisAlignedBB side_aabb, int railing_height_extension) public HorizontalFourWayWaterLoggable(long config, AbstractBlock.Properties properties, AxisAlignedBB base_aabb, final AxisAlignedBB side_aabb, int railing_height_extension)
{ {
super(config, properties, base_aabb); super(config, properties, base_aabb);
Map<BlockState, VoxelShape> build_shapes = new HashMap<>(); Map<BlockState, VoxelShape> build_shapes = new HashMap<>();
Map<BlockState, VoxelShape> build_collision_shapes = new HashMap<>(); Map<BlockState, VoxelShape> build_collision_shapes = new HashMap<>();
for(BlockState state:getStateContainer().getValidStates()) { for(BlockState state:getStateDefinition().getPossibleStates()) {
{ {
VoxelShape shape = ((base_aabb.getXSize()==0) || (base_aabb.getYSize()==0) || (base_aabb.getZSize()==0)) ? VoxelShapes.empty() : VoxelShapes.create(base_aabb); VoxelShape shape = ((base_aabb.getXsize()==0) || (base_aabb.getYsize()==0) || (base_aabb.getZsize()==0)) ? VoxelShapes.empty() : VoxelShapes.create(base_aabb);
if(state.get(NORTH)) shape = VoxelShapes.combine(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.NORTH, true)), IBooleanFunction.OR); if(state.getValue(NORTH)) shape = VoxelShapes.joinUnoptimized(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.NORTH, true)), IBooleanFunction.OR);
if(state.get(EAST)) shape = VoxelShapes.combine(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.EAST, true)), IBooleanFunction.OR); if(state.getValue(EAST)) shape = VoxelShapes.joinUnoptimized(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.EAST, true)), IBooleanFunction.OR);
if(state.get(SOUTH)) shape = VoxelShapes.combine(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.SOUTH, true)), IBooleanFunction.OR); if(state.getValue(SOUTH)) shape = VoxelShapes.joinUnoptimized(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.SOUTH, true)), IBooleanFunction.OR);
if(state.get(WEST)) shape = VoxelShapes.combine(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.WEST, true)), IBooleanFunction.OR); if(state.getValue(WEST)) shape = VoxelShapes.joinUnoptimized(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.WEST, true)), IBooleanFunction.OR);
if(shape.isEmpty()) shape = VoxelShapes.fullCube(); if(shape.isEmpty()) shape = VoxelShapes.block();
build_shapes.put(state.with(WATERLOGGED, false), shape); build_shapes.put(state.setValue(WATERLOGGED, false), shape);
build_shapes.put(state.with(WATERLOGGED, true), shape); build_shapes.put(state.setValue(WATERLOGGED, true), shape);
} }
{ {
// how the hack to extend a shape, these are the above with y+4px. // how the hack to extend a shape, these are the above with y+4px.
VoxelShape shape = ((base_aabb.getXSize()==0) || (base_aabb.getYSize()==0) || (base_aabb.getZSize()==0)) ? VoxelShapes.empty() : VoxelShapes.create(base_aabb); VoxelShape shape = ((base_aabb.getXsize()==0) || (base_aabb.getYsize()==0) || (base_aabb.getZsize()==0)) ? VoxelShapes.empty() : VoxelShapes.create(base_aabb);
if(state.get(NORTH)) shape = VoxelShapes.combine(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.NORTH, true).expand(0, railing_height_extension, 0)), IBooleanFunction.OR); if(state.getValue(NORTH)) shape = VoxelShapes.joinUnoptimized(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.NORTH, true).expandTowards(0, railing_height_extension, 0)), IBooleanFunction.OR);
if(state.get(EAST)) shape = VoxelShapes.combine(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.EAST, true).expand(0, railing_height_extension, 0)), IBooleanFunction.OR); if(state.getValue(EAST)) shape = VoxelShapes.joinUnoptimized(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.EAST, true).expandTowards(0, railing_height_extension, 0)), IBooleanFunction.OR);
if(state.get(SOUTH)) shape = VoxelShapes.combine(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.SOUTH, true).expand(0, railing_height_extension, 0)), IBooleanFunction.OR); if(state.getValue(SOUTH)) shape = VoxelShapes.joinUnoptimized(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.SOUTH, true).expandTowards(0, railing_height_extension, 0)), IBooleanFunction.OR);
if(state.get(WEST)) shape = VoxelShapes.combine(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.WEST, true).expand(0, railing_height_extension, 0)), IBooleanFunction.OR); if(state.getValue(WEST)) shape = VoxelShapes.joinUnoptimized(shape,VoxelShapes.create(Auxiliaries.getRotatedAABB(side_aabb, Direction.WEST, true).expandTowards(0, railing_height_extension, 0)), IBooleanFunction.OR);
if(shape.isEmpty()) shape = VoxelShapes.fullCube(); if(shape.isEmpty()) shape = VoxelShapes.block();
build_collision_shapes.put(state.with(WATERLOGGED, false), shape); build_collision_shapes.put(state.setValue(WATERLOGGED, false), shape);
build_collision_shapes.put(state.with(WATERLOGGED, true), shape); build_collision_shapes.put(state.setValue(WATERLOGGED, true), shape);
} }
} }
shapes = build_shapes; shapes = build_shapes;
collision_shapes = build_collision_shapes; collision_shapes = build_collision_shapes;
setDefaultState(super.getDefaultState().with(NORTH, false).with(EAST, false).with(SOUTH, false).with(WEST, false).with(WATERLOGGED, false)); registerDefaultState(super.defaultBlockState().setValue(NORTH, false).setValue(EAST, false).setValue(SOUTH, false).setValue(WEST, false).setValue(WATERLOGGED, false));
} }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(NORTH,EAST,SOUTH,WEST); } { super.createBlockStateDefinition(builder); builder.add(NORTH,EAST,SOUTH,WEST); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ return super.getStateForPlacement(context).with(NORTH, false).with(EAST, false).with(SOUTH, false).with(WEST, false); } { return super.getStateForPlacement(context).setValue(NORTH, false).setValue(EAST, false).setValue(SOUTH, false).setValue(WEST, false); }
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context)
{ return shapes.getOrDefault(state, VoxelShapes.fullCube()); } { return shapes.getOrDefault(state, VoxelShapes.block()); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) public VoxelShape getCollisionShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context)
{ return collision_shapes.getOrDefault(state, VoxelShapes.fullCube()); } { return collision_shapes.getOrDefault(state, VoxelShapes.block()); }
public static BooleanProperty getDirectionProperty(Direction face) public static BooleanProperty getDirectionProperty(Direction face)
{ {

View file

@ -44,7 +44,7 @@ public class StandardDoorBlock extends DoorBlock implements StandardBlocks.IStan
protected final SoundEvent open_sound_; protected final SoundEvent open_sound_;
protected final SoundEvent close_sound_; protected final SoundEvent close_sound_;
public StandardDoorBlock(long config, Block.Properties properties, AxisAlignedBB[] open_aabbs_top, AxisAlignedBB[] open_aabbs_bottom, AxisAlignedBB[] closed_aabbs_top, AxisAlignedBB[] closed_aabbs_bottom, SoundEvent open_sound, SoundEvent close_sound) public StandardDoorBlock(long config, AbstractBlock.Properties properties, AxisAlignedBB[] open_aabbs_top, AxisAlignedBB[] open_aabbs_bottom, AxisAlignedBB[] closed_aabbs_top, AxisAlignedBB[] closed_aabbs_bottom, SoundEvent open_sound, SoundEvent close_sound)
{ {
super(properties); super(properties);
VoxelShape shapes[][][][] = new VoxelShape[Direction.values().length][2][2][2]; VoxelShape shapes[][][][] = new VoxelShape[Direction.values().length][2][2][2];
@ -54,13 +54,13 @@ public class StandardDoorBlock extends DoorBlock implements StandardBlocks.IStan
for(boolean hinge_right: new boolean[]{false,true}) { for(boolean hinge_right: new boolean[]{false,true}) {
VoxelShape shape = VoxelShapes.empty(); VoxelShape shape = VoxelShapes.empty();
if(facing.getAxis() == Axis.Y) { if(facing.getAxis() == Axis.Y) {
shape = VoxelShapes.fullCube(); shape = VoxelShapes.block();
} else { } else {
final AxisAlignedBB[] aabbs = (open)?((half==DoubleBlockHalf.UPPER) ? open_aabbs_top : open_aabbs_bottom) : ((half==DoubleBlockHalf.UPPER) ? closed_aabbs_top : closed_aabbs_bottom); final AxisAlignedBB[] aabbs = (open)?((half==DoubleBlockHalf.UPPER) ? open_aabbs_top : open_aabbs_bottom) : ((half==DoubleBlockHalf.UPPER) ? closed_aabbs_top : closed_aabbs_bottom);
for(AxisAlignedBB e:aabbs) { for(AxisAlignedBB e:aabbs) {
AxisAlignedBB aabb = Auxiliaries.getRotatedAABB(e, facing, true); AxisAlignedBB aabb = Auxiliaries.getRotatedAABB(e, facing, true);
if(!hinge_right) aabb = Auxiliaries.getMirroredAABB(aabb, facing.rotateY().getAxis()); if(!hinge_right) aabb = Auxiliaries.getMirroredAABB(aabb, facing.getClockWise().getAxis());
shape = VoxelShapes.combineAndSimplify(shape, VoxelShapes.create(aabb), IBooleanFunction.OR); shape = VoxelShapes.join(shape, VoxelShapes.create(aabb), IBooleanFunction.OR);
} }
} }
shapes[facing.ordinal()][open?1:0][hinge_right?1:0][half==DoubleBlockHalf.UPPER?0:1] = shape; shapes[facing.ordinal()][open?1:0][hinge_right?1:0][half==DoubleBlockHalf.UPPER?0:1] = shape;
@ -74,10 +74,10 @@ public class StandardDoorBlock extends DoorBlock implements StandardBlocks.IStan
close_sound_ = close_sound; close_sound_ = close_sound;
} }
public StandardDoorBlock(long config, Block.Properties properties, AxisAlignedBB open_aabb, AxisAlignedBB closed_aabb, SoundEvent open_sound, SoundEvent close_sound) public StandardDoorBlock(long config, AbstractBlock.Properties properties, AxisAlignedBB open_aabb, AxisAlignedBB closed_aabb, SoundEvent open_sound, SoundEvent close_sound)
{ this(config, properties, new AxisAlignedBB[]{open_aabb}, new AxisAlignedBB[]{open_aabb}, new AxisAlignedBB[]{closed_aabb}, new AxisAlignedBB[]{closed_aabb}, open_sound, close_sound); } { this(config, properties, new AxisAlignedBB[]{open_aabb}, new AxisAlignedBB[]{open_aabb}, new AxisAlignedBB[]{closed_aabb}, new AxisAlignedBB[]{closed_aabb}, open_sound, close_sound); }
public StandardDoorBlock(long config, Block.Properties properties, SoundEvent open_sound, SoundEvent close_sound) public StandardDoorBlock(long config, AbstractBlock.Properties properties, SoundEvent open_sound, SoundEvent close_sound)
{ {
this( this(
config, properties, config, properties,
@ -88,14 +88,14 @@ public class StandardDoorBlock extends DoorBlock implements StandardBlocks.IStan
); );
} }
public StandardDoorBlock(long config, Block.Properties properties) public StandardDoorBlock(long config, AbstractBlock.Properties properties)
{ {
this( this(
config, properties, config, properties,
Auxiliaries.getPixeledAABB(13,0, 0, 16,16,16), Auxiliaries.getPixeledAABB(13,0, 0, 16,16,16),
Auxiliaries.getPixeledAABB( 0,0,13, 16,16,16), Auxiliaries.getPixeledAABB( 0,0,13, 16,16,16),
SoundEvents.BLOCK_WOODEN_DOOR_OPEN, SoundEvents.WOODEN_DOOR_OPEN,
SoundEvents.BLOCK_WOODEN_DOOR_CLOSE SoundEvents.WOODEN_DOOR_CLOSE
); );
} }
@ -110,21 +110,21 @@ public class StandardDoorBlock extends DoorBlock implements StandardBlocks.IStan
{ {
if(!(world_ro instanceof World)) return; if(!(world_ro instanceof World)) return;
final World world = (World)world_ro; final World world = (World)world_ro;
final BlockPos adjecent_pos = pos.offset( (state.get(HINGE)==DoorHingeSide.LEFT) ? (state.get(FACING).rotateY()) : (state.get(FACING).rotateYCCW())); final BlockPos adjecent_pos = pos.relative( (state.getValue(HINGE)==DoorHingeSide.LEFT) ? (state.getValue(FACING).getClockWise()) : (state.getValue(FACING).getCounterClockWise()));
if(!world.isBlockPresent(adjecent_pos)) return; if(!world.isLoaded(adjecent_pos)) return;
BlockState adjacent_state = world.getBlockState(adjecent_pos); BlockState adjacent_state = world.getBlockState(adjecent_pos);
if(adjacent_state.getBlock()!=this) return; if(adjacent_state.getBlock()!=this) return;
if(adjacent_state.get(OPEN)==open) return; if(adjacent_state.getValue(OPEN)==open) return;
world.setBlockState(adjecent_pos, adjacent_state.with(OPEN, open), 2|10); world.setBlock(adjecent_pos, adjacent_state.setValue(OPEN, open), 2|10);
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); } { Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@ -133,28 +133,28 @@ public class StandardDoorBlock extends DoorBlock implements StandardBlocks.IStan
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext context) public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext context)
{ return shapes_[state.get(FACING).ordinal()][state.get(OPEN)?1:0][state.get(HINGE)==DoorHingeSide.RIGHT?1:0][state.get(HALF)==DoubleBlockHalf.UPPER?0:1]; } { return shapes_[state.getValue(FACING).ordinal()][state.getValue(OPEN)?1:0][state.getValue(HINGE)==DoorHingeSide.RIGHT?1:0][state.getValue(HALF)==DoubleBlockHalf.UPPER?0:1]; }
@Override @Override
public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit)
{ openDoor(world, state, pos, !state.get(OPEN)); return ActionResultType.func_233537_a_(world.isRemote()); } { setOpen(world, state, pos, !state.getValue(OPEN)); return ActionResultType.sidedSuccess(world.isClientSide()); }
@Override @Override
public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) public void neighborChanged(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving)
{ {
boolean powered = world.isBlockPowered(pos) || world.isBlockPowered(pos.offset(state.get(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN)); boolean powered = world.hasNeighborSignal(pos) || world.hasNeighborSignal(pos.relative(state.getValue(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN));
if((block == this) || (powered == state.get(POWERED))) return; if((block == this) || (powered == state.getValue(POWERED))) return;
world.setBlockState(pos, state.with(POWERED, powered).with(OPEN, powered), 2); world.setBlock(pos, state.setValue(POWERED, powered).setValue(OPEN, powered), 2);
actuate_adjacent_wing(state, world, pos, powered); actuate_adjacent_wing(state, world, pos, powered);
if(powered != state.get(OPEN)) sound(world, pos, powered); if(powered != state.getValue(OPEN)) sound(world, pos, powered);
} }
@Override @Override
public void openDoor(World world, BlockState state, BlockPos pos, boolean open) public void setOpen(World world, BlockState state, BlockPos pos, boolean open)
{ {
if(!state.isIn(this) || (state.get(OPEN) == open)) return; if(!state.is(this) || (state.getValue(OPEN) == open)) return;
state = state.with(OPEN, open); state = state.setValue(OPEN, open);
world.setBlockState(pos, state, 2|8); world.setBlock(pos, state, 2|8);
sound(world, pos, open); sound(world, pos, open);
actuate_adjacent_wing(state, world, pos, open); actuate_adjacent_wing(state, world, pos, open);
} }

View file

@ -42,19 +42,19 @@ import java.util.*;
public class StandardFenceBlock extends WallBlock implements StandardBlocks.IStandardBlock public class StandardFenceBlock extends WallBlock implements StandardBlocks.IStandardBlock
{ {
public static final BooleanProperty UP = BlockStateProperties.UP; public static final BooleanProperty UP = BlockStateProperties.UP;
public static final EnumProperty<WallHeight> WALL_EAST = BlockStateProperties.WALL_HEIGHT_EAST; public static final EnumProperty<WallHeight> WALL_EAST = BlockStateProperties.EAST_WALL;
public static final EnumProperty<WallHeight> WALL_NORTH = BlockStateProperties.WALL_HEIGHT_NORTH; public static final EnumProperty<WallHeight> WALL_NORTH = BlockStateProperties.NORTH_WALL;
public static final EnumProperty<WallHeight> WALL_SOUTH = BlockStateProperties.WALL_HEIGHT_SOUTH; public static final EnumProperty<WallHeight> WALL_SOUTH = BlockStateProperties.SOUTH_WALL;
public static final EnumProperty<WallHeight> WALL_WEST = BlockStateProperties.WALL_HEIGHT_WEST; public static final EnumProperty<WallHeight> WALL_WEST = BlockStateProperties.WEST_WALL;
public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
private final Map<BlockState, VoxelShape> shape_voxels; private final Map<BlockState, VoxelShape> shape_voxels;
private final Map<BlockState, VoxelShape> collision_shape_voxels; private final Map<BlockState, VoxelShape> collision_shape_voxels;
private final long config; private final long config;
public StandardFenceBlock(long config, Block.Properties properties) public StandardFenceBlock(long config, AbstractBlock.Properties properties)
{ this(config, properties, 1.5,16, 1.5, 0, 14, 16); } { this(config, properties, 1.5,16, 1.5, 0, 14, 16); }
public StandardFenceBlock(long config, Block.Properties properties, double pole_width, double pole_height, double side_width, double side_min_y, double side_max_low_y, double side_max_tall_y) public StandardFenceBlock(long config, AbstractBlock.Properties properties, double pole_width, double pole_height, double side_width, double side_min_y, double side_max_low_y, double side_max_tall_y)
{ {
super(properties); super(properties);
shape_voxels = buildShapes(pole_width, pole_height, side_width, side_min_y, side_max_low_y, side_max_tall_y); shape_voxels = buildShapes(pole_width, pole_height, side_width, side_min_y, side_max_low_y, side_max_tall_y);
@ -68,7 +68,7 @@ public class StandardFenceBlock extends WallBlock implements StandardBlocks.ISta
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); } { Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); }
private static VoxelShape combinedShape(VoxelShape pole, WallHeight height, VoxelShape low, VoxelShape high) private static VoxelShape combinedShape(VoxelShape pole, WallHeight height, VoxelShape low, VoxelShape high)
@ -81,34 +81,34 @@ public class StandardFenceBlock extends WallBlock implements StandardBlocks.ISta
protected Map<BlockState, VoxelShape> buildShapes(double pole_width, double pole_height, double side_width, double side_min_y, double side_max_low_y, double side_max_tall_y) protected Map<BlockState, VoxelShape> buildShapes(double pole_width, double pole_height, double side_width, double side_min_y, double side_max_low_y, double side_max_tall_y)
{ {
final double px0=8.0-pole_width, px1=8.0+pole_width, sx0=8.0-side_width, sx1=8.0+side_width; final double px0=8.0-pole_width, px1=8.0+pole_width, sx0=8.0-side_width, sx1=8.0+side_width;
VoxelShape vp = Block.makeCuboidShape(px0, 0, px0, px1, pole_height, px1); VoxelShape vp = Block.box(px0, 0, px0, px1, pole_height, px1);
VoxelShape vs1 = Block.makeCuboidShape(sx0, side_min_y, 0, sx1, side_max_low_y, sx1); VoxelShape vs1 = Block.box(sx0, side_min_y, 0, sx1, side_max_low_y, sx1);
VoxelShape vs2 = Block.makeCuboidShape(sx0, side_min_y, sx0, sx1, side_max_low_y, 16); VoxelShape vs2 = Block.box(sx0, side_min_y, sx0, sx1, side_max_low_y, 16);
VoxelShape vs3 = Block.makeCuboidShape(0, side_min_y, sx0, sx1, side_max_low_y, sx1); VoxelShape vs3 = Block.box(0, side_min_y, sx0, sx1, side_max_low_y, sx1);
VoxelShape vs4 = Block.makeCuboidShape(sx0, side_min_y, sx0, 16, side_max_low_y, sx1); VoxelShape vs4 = Block.box(sx0, side_min_y, sx0, 16, side_max_low_y, sx1);
VoxelShape vs5 = Block.makeCuboidShape(sx0, side_min_y, 0, sx1, side_max_tall_y, sx1); VoxelShape vs5 = Block.box(sx0, side_min_y, 0, sx1, side_max_tall_y, sx1);
VoxelShape vs6 = Block.makeCuboidShape(sx0, side_min_y, sx0, sx1, side_max_tall_y, 16); VoxelShape vs6 = Block.box(sx0, side_min_y, sx0, sx1, side_max_tall_y, 16);
VoxelShape vs7 = Block.makeCuboidShape(0, side_min_y, sx0, sx1, side_max_tall_y, sx1); VoxelShape vs7 = Block.box(0, side_min_y, sx0, sx1, side_max_tall_y, sx1);
VoxelShape vs8 = Block.makeCuboidShape(sx0, side_min_y, sx0, 16, side_max_tall_y, sx1); VoxelShape vs8 = Block.box(sx0, side_min_y, sx0, 16, side_max_tall_y, sx1);
Builder<BlockState, VoxelShape> builder = ImmutableMap.builder(); Builder<BlockState, VoxelShape> builder = ImmutableMap.builder();
for(Boolean up : UP.getAllowedValues()) { for(Boolean up : UP.getPossibleValues()) {
for(WallHeight wh_east : WALL_EAST.getAllowedValues()) { for(WallHeight wh_east : WALL_EAST.getPossibleValues()) {
for(WallHeight wh_north : WALL_NORTH.getAllowedValues()) { for(WallHeight wh_north : WALL_NORTH.getPossibleValues()) {
for(WallHeight wh_west : WALL_WEST.getAllowedValues()) { for(WallHeight wh_west : WALL_WEST.getPossibleValues()) {
for(WallHeight wh_south : WALL_SOUTH.getAllowedValues()) { for(WallHeight wh_south : WALL_SOUTH.getPossibleValues()) {
VoxelShape shape = VoxelShapes.empty(); VoxelShape shape = VoxelShapes.empty();
shape = combinedShape(shape, wh_east, vs4, vs8); shape = combinedShape(shape, wh_east, vs4, vs8);
shape = combinedShape(shape, wh_west, vs3, vs7); shape = combinedShape(shape, wh_west, vs3, vs7);
shape = combinedShape(shape, wh_north, vs1, vs5); shape = combinedShape(shape, wh_north, vs1, vs5);
shape = combinedShape(shape, wh_south, vs2, vs6); shape = combinedShape(shape, wh_south, vs2, vs6);
if(up) shape = VoxelShapes.or(shape, vp); if(up) shape = VoxelShapes.or(shape, vp);
BlockState bs = getDefaultState().with(UP, up) BlockState bs = defaultBlockState().setValue(UP, up)
.with(WALL_EAST, wh_east) .setValue(WALL_EAST, wh_east)
.with(WALL_NORTH, wh_north) .setValue(WALL_NORTH, wh_north)
.with(WALL_WEST, wh_west) .setValue(WALL_WEST, wh_west)
.with(WALL_SOUTH, wh_south); .setValue(WALL_SOUTH, wh_south);
builder.put(bs.with(WATERLOGGED, false), shape); builder.put(bs.setValue(WATERLOGGED, false), shape);
builder.put(bs.with(WATERLOGGED, true), shape); builder.put(bs.setValue(WATERLOGGED, true), shape);
} }
} }
} }
@ -119,23 +119,23 @@ public class StandardFenceBlock extends WallBlock implements StandardBlocks.ISta
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return shape_voxels.getOrDefault(state, VoxelShapes.fullCube()); } { return shape_voxels.getOrDefault(state, VoxelShapes.block()); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return collision_shape_voxels.getOrDefault(state, VoxelShapes.fullCube()); } { return collision_shape_voxels.getOrDefault(state, VoxelShapes.block()); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); } { super.createBlockStateDefinition(builder); }
protected boolean attachesTo(BlockState facingState, IWorldReader world, BlockPos facingPos, Direction side) protected boolean attachesTo(BlockState facingState, IWorldReader world, BlockPos facingPos, Direction side)
{ {
final Block block = facingState.getBlock(); final Block block = facingState.getBlock();
if((block instanceof FenceGateBlock) || (block instanceof StandardFenceBlock) || (block instanceof VariantWallBlock)) return true; if((block instanceof FenceGateBlock) || (block instanceof StandardFenceBlock) || (block instanceof VariantWallBlock)) return true;
final BlockState oppositeState = world.getBlockState(facingPos.offset(side, 2)); final BlockState oppositeState = world.getBlockState(facingPos.relative(side, 2));
if(!(oppositeState.getBlock() instanceof StandardFenceBlock)) return false; if(!(oppositeState.getBlock() instanceof StandardFenceBlock)) return false;
return facingState.isNormalCube(world, facingPos) && hasEnoughSolidSide(world, facingPos, side); return facingState.isRedstoneConductor(world, facingPos) && canSupportCenter(world, facingPos, side);
} }
protected WallHeight selectWallHeight(IWorldReader world, BlockPos pos, Direction direction) protected WallHeight selectWallHeight(IWorldReader world, BlockPos pos, Direction direction)
@ -145,38 +145,38 @@ public class StandardFenceBlock extends WallBlock implements StandardBlocks.ISta
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
IWorldReader world = context.getWorld(); IWorldReader world = context.getLevel();
BlockPos pos = context.getPos(); BlockPos pos = context.getClickedPos();
FluidState fs = context.getWorld().getFluidState(context.getPos()); FluidState fs = context.getLevel().getFluidState(context.getClickedPos());
boolean n = attachesTo(world.getBlockState(pos.north()), world, pos.north(), Direction.SOUTH); boolean n = attachesTo(world.getBlockState(pos.north()), world, pos.north(), Direction.SOUTH);
boolean e = attachesTo(world.getBlockState(pos.east()), world, pos.east(), Direction.WEST); boolean e = attachesTo(world.getBlockState(pos.east()), world, pos.east(), Direction.WEST);
boolean s = attachesTo(world.getBlockState(pos.south()), world, pos.south(), Direction.NORTH); boolean s = attachesTo(world.getBlockState(pos.south()), world, pos.south(), Direction.NORTH);
boolean w = attachesTo(world.getBlockState(pos.west()), world, pos.west(), Direction.EAST); boolean w = attachesTo(world.getBlockState(pos.west()), world, pos.west(), Direction.EAST);
boolean not_straight = (!n || !s || e || w) && (n || s || !e || !w); boolean not_straight = (!n || !s || e || w) && (n || s || !e || !w);
return getDefaultState() return defaultBlockState()
.with(UP, not_straight) .setValue(UP, not_straight)
.with(WALL_NORTH, n ? selectWallHeight(world, pos, Direction.NORTH) : WallHeight.NONE) .setValue(WALL_NORTH, n ? selectWallHeight(world, pos, Direction.NORTH) : WallHeight.NONE)
.with(WALL_EAST , e ? selectWallHeight(world, pos, Direction.EAST) : WallHeight.NONE) .setValue(WALL_EAST , e ? selectWallHeight(world, pos, Direction.EAST) : WallHeight.NONE)
.with(WALL_SOUTH, s ? selectWallHeight(world, pos, Direction.SOUTH) : WallHeight.NONE) .setValue(WALL_SOUTH, s ? selectWallHeight(world, pos, Direction.SOUTH) : WallHeight.NONE)
.with(WALL_WEST , w ? selectWallHeight(world, pos, Direction.WEST) : WallHeight.NONE) .setValue(WALL_WEST , w ? selectWallHeight(world, pos, Direction.WEST) : WallHeight.NONE)
.with(WATERLOGGED, fs.getFluid() == Fluids.WATER); .setValue(WATERLOGGED, fs.getType() == Fluids.WATER);
} }
@Override @Override
public BlockState updatePostPlacement(BlockState state, Direction side, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos) public BlockState updateShape(BlockState state, Direction side, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos)
{ {
if(state.get(BlockStateProperties.WATERLOGGED)) world.getPendingFluidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickRate(world)); if(state.getValue(BlockStateProperties.WATERLOGGED)) world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world));
if(side == Direction.DOWN) return super.updatePostPlacement(state, side, facingState, world, pos, facingPos); if(side == Direction.DOWN) return super.updateShape(state, side, facingState, world, pos, facingPos);
boolean n = (side==Direction.NORTH) ? attachesTo(facingState, world, facingPos, side) : (state.get(WALL_NORTH)!=WallHeight.NONE); boolean n = (side==Direction.NORTH) ? attachesTo(facingState, world, facingPos, side) : (state.getValue(WALL_NORTH)!=WallHeight.NONE);
boolean e = (side==Direction.EAST) ? attachesTo(facingState, world, facingPos, side) : (state.get(WALL_EAST) !=WallHeight.NONE); boolean e = (side==Direction.EAST) ? attachesTo(facingState, world, facingPos, side) : (state.getValue(WALL_EAST) !=WallHeight.NONE);
boolean s = (side==Direction.SOUTH) ? attachesTo(facingState, world, facingPos, side) : (state.get(WALL_SOUTH)!=WallHeight.NONE); boolean s = (side==Direction.SOUTH) ? attachesTo(facingState, world, facingPos, side) : (state.getValue(WALL_SOUTH)!=WallHeight.NONE);
boolean w = (side==Direction.WEST) ? attachesTo(facingState, world, facingPos, side) : (state.get(WALL_WEST) !=WallHeight.NONE); boolean w = (side==Direction.WEST) ? attachesTo(facingState, world, facingPos, side) : (state.getValue(WALL_WEST) !=WallHeight.NONE);
boolean not_straight = (!n || !s || e || w) && (n || s || !e || !w); boolean not_straight = (!n || !s || e || w) && (n || s || !e || !w);
return state.with(UP, not_straight) return state.setValue(UP, not_straight)
.with(WALL_NORTH, n ? selectWallHeight(world, pos, Direction.NORTH) : WallHeight.NONE) .setValue(WALL_NORTH, n ? selectWallHeight(world, pos, Direction.NORTH) : WallHeight.NONE)
.with(WALL_EAST , e ? selectWallHeight(world, pos, Direction.EAST) : WallHeight.NONE) .setValue(WALL_EAST , e ? selectWallHeight(world, pos, Direction.EAST) : WallHeight.NONE)
.with(WALL_SOUTH, s ? selectWallHeight(world, pos, Direction.SOUTH) : WallHeight.NONE) .setValue(WALL_SOUTH, s ? selectWallHeight(world, pos, Direction.SOUTH) : WallHeight.NONE)
.with(WALL_WEST , w ? selectWallHeight(world, pos, Direction.WEST) : WallHeight.NONE); .setValue(WALL_WEST , w ? selectWallHeight(world, pos, Direction.WEST) : WallHeight.NONE);
} }
@Override @Override
@ -184,11 +184,11 @@ public class StandardFenceBlock extends WallBlock implements StandardBlocks.ISta
{ return false; } { return false; }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public PushReaction getPushReaction(BlockState state) public PushReaction getPistonPushReaction(BlockState state)
{ return PushReaction.NORMAL; } { return PushReaction.NORMAL; }
} }

View file

@ -29,19 +29,19 @@ public class StandardStairsBlock extends StairsBlock implements StandardBlocks.I
{ {
private final long config; private final long config;
public StandardStairsBlock(long config, BlockState state, Block.Properties properties) public StandardStairsBlock(long config, BlockState state, AbstractBlock.Properties properties)
{ super(()->state, properties); this.config = config; } { super(()->state, properties); this.config = config; }
public StandardStairsBlock(long config, java.util.function.Supplier<BlockState> state, Block.Properties properties) public StandardStairsBlock(long config, java.util.function.Supplier<BlockState> state, AbstractBlock.Properties properties)
{ super(state, properties); this.config = config; } { super(state, properties); this.config = config; }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); } { Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@ -50,6 +50,6 @@ public class StandardStairsBlock extends StairsBlock implements StandardBlocks.I
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public PushReaction getPushReaction(BlockState state) public PushReaction getPistonPushReaction(BlockState state)
{ return PushReaction.NORMAL; } { return PushReaction.NORMAL; }
} }

View file

@ -44,6 +44,8 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import wile.engineersdecor.libmc.blocks.StandardBlocks.IStandardBlock.RenderTypeHint;
public class VariantSlabBlock extends StandardBlocks.WaterLoggable implements StandardBlocks.IStandardBlock public class VariantSlabBlock extends StandardBlocks.WaterLoggable implements StandardBlocks.IStandardBlock
{ {
public static final EnumProperty<SlabType> TYPE = BlockStateProperties.SLAB_TYPE; public static final EnumProperty<SlabType> TYPE = BlockStateProperties.SLAB_TYPE;
@ -62,10 +64,10 @@ public class VariantSlabBlock extends StandardBlocks.WaterLoggable implements St
{ with_pickup = direct_slab_pickup; } { with_pickup = direct_slab_pickup; }
protected boolean is_cube(BlockState state) protected boolean is_cube(BlockState state)
{ return state.get(TYPE) == SlabType.DOUBLE; } { return state.getValue(TYPE) == SlabType.DOUBLE; }
public VariantSlabBlock(long config, Block.Properties builder) public VariantSlabBlock(long config, AbstractBlock.Properties builder)
{ super(config, builder); setDefaultState(getDefaultState().with(TYPE, SlabType.BOTTOM)); } { super(config, builder); registerDefaultState(defaultBlockState().setValue(TYPE, SlabType.BOTTOM)); }
@Override @Override
public RenderTypeHint getRenderTypeHint() public RenderTypeHint getRenderTypeHint()
@ -73,7 +75,7 @@ public class VariantSlabBlock extends StandardBlocks.WaterLoggable implements St
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ {
if(!Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true)) return; if(!Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true)) return;
if(with_pickup) Auxiliaries.Tooltip.addInformation("engineersdecor.tooltip.slabpickup", "engineersdecor.tooltip.slabpickup", tooltip, flag, true); if(with_pickup) Auxiliaries.Tooltip.addInformation("engineersdecor.tooltip.slabpickup", "engineersdecor.tooltip.slabpickup", tooltip, flag, true);
@ -82,11 +84,11 @@ public class VariantSlabBlock extends StandardBlocks.WaterLoggable implements St
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean isSideInvisible(BlockState state, BlockState adjacentBlockState, Direction side) public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side)
{ return (adjacentBlockState==state) ? true : super.isSideInvisible(state, adjacentBlockState, side); } { return (adjacentBlockState==state) ? true : super.skipRendering(state, adjacentBlockState, side); }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@ -95,44 +97,44 @@ public class VariantSlabBlock extends StandardBlocks.WaterLoggable implements St
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getShape(BlockState state, IBlockReader source, BlockPos pos, ISelectionContext selectionContext)
{ return AABBs[state.get(TYPE).ordinal() & 0x3]; } { return AABBs[state.getValue(TYPE).ordinal() & 0x3]; }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return getShape(state, world, pos, selectionContext); } { return getShape(state, world, pos, selectionContext); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(TYPE, TEXTURE_VARIANT); } { super.createBlockStateDefinition(builder); builder.add(TYPE, TEXTURE_VARIANT); }
@Override @Override
@Nullable @Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
BlockPos pos = context.getPos(); BlockPos pos = context.getClickedPos();
if(context.getWorld().getBlockState(pos).getBlock() == this) return context.getWorld().getBlockState(pos).with(TYPE, SlabType.DOUBLE).with(WATERLOGGED, false); if(context.getLevel().getBlockState(pos).getBlock() == this) return context.getLevel().getBlockState(pos).setValue(TYPE, SlabType.DOUBLE).setValue(WATERLOGGED, false);
final int rnd = MathHelper.clamp((int)(MathHelper.getPositionRandom(context.getPos()) & 0x3), 0, 3); final int rnd = MathHelper.clamp((int)(MathHelper.getSeed(context.getClickedPos()) & 0x3), 0, 3);
final Direction face = context.getFace(); final Direction face = context.getClickedFace();
final BlockState placement_state = super.getStateForPlacement(context).with(TEXTURE_VARIANT, rnd); // fluid state final BlockState placement_state = super.getStateForPlacement(context).setValue(TEXTURE_VARIANT, rnd); // fluid state
if(face == Direction.UP) return placement_state.with(TYPE, SlabType.BOTTOM); if(face == Direction.UP) return placement_state.setValue(TYPE, SlabType.BOTTOM);
if(face == Direction.DOWN) return placement_state.with(TYPE, SlabType.TOP); if(face == Direction.DOWN) return placement_state.setValue(TYPE, SlabType.TOP);
if(!face.getAxis().isHorizontal()) return placement_state; if(!face.getAxis().isHorizontal()) return placement_state;
final boolean isupper = ((context.getHitVec().getY() - context.getPos().getY()) > 0.5); final boolean isupper = ((context.getClickLocation().y() - context.getClickedPos().getY()) > 0.5);
return placement_state.with(TYPE, isupper ? SlabType.TOP : SlabType.BOTTOM); return placement_state.setValue(TYPE, isupper ? SlabType.TOP : SlabType.BOTTOM);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean isReplaceable(BlockState state, BlockItemUseContext context) public boolean canBeReplaced(BlockState state, BlockItemUseContext context)
{ {
if(context.getItem().getItem() != this.asItem()) return false; if(context.getItemInHand().getItem() != this.asItem()) return false;
if(!context.replacingClickedOnBlock()) return true; if(!context.replacingClickedOnBlock()) return true;
final Direction face = context.getFace(); final Direction face = context.getClickedFace();
final SlabType type = state.get(TYPE); final SlabType type = state.getValue(TYPE);
if((face == Direction.UP) && (type==SlabType.BOTTOM)) return true; if((face == Direction.UP) && (type==SlabType.BOTTOM)) return true;
if((face == Direction.DOWN) && (type==SlabType.TOP)) return true; if((face == Direction.DOWN) && (type==SlabType.TOP)) return true;
if(!face.getAxis().isHorizontal()) return false; if(!face.getAxis().isHorizontal()) return false;
final boolean isupper = ((context.getHitVec().getY() - context.getPos().getY()) > 0.5); final boolean isupper = ((context.getClickLocation().y() - context.getClickedPos().getY()) > 0.5);
return isupper ? (type==SlabType.BOTTOM) : (type==SlabType.TOP); return isupper ? (type==SlabType.BOTTOM) : (type==SlabType.TOP);
} }
@ -152,48 +154,48 @@ public class VariantSlabBlock extends StandardBlocks.WaterLoggable implements St
@Override @Override
public List<ItemStack> dropList(BlockState state, World world, TileEntity te, boolean explosion) public List<ItemStack> dropList(BlockState state, World world, TileEntity te, boolean explosion)
{ return new ArrayList<ItemStack>(Collections.singletonList(new ItemStack(this.asItem(), num_slabs_contained_in_parts_[state.get(TYPE).ordinal() & 0x3]))); } { return new ArrayList<ItemStack>(Collections.singletonList(new ItemStack(this.asItem(), num_slabs_contained_in_parts_[state.getValue(TYPE).ordinal() & 0x3]))); }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void onBlockClicked(BlockState state, World world, BlockPos pos, PlayerEntity player) public void attack(BlockState state, World world, BlockPos pos, PlayerEntity player)
{ {
if((world.isRemote) || (!with_pickup)) return; if((world.isClientSide) || (!with_pickup)) return;
final ItemStack stack = player.getHeldItemMainhand(); final ItemStack stack = player.getMainHandItem();
if(stack.isEmpty() || (Block.getBlockFromItem(stack.getItem()) != this)) return; if(stack.isEmpty() || (Block.byItem(stack.getItem()) != this)) return;
if(stack.getCount() >= stack.getMaxStackSize()) return; if(stack.getCount() >= stack.getMaxStackSize()) return;
Vector3d lv = player.getLookVec(); Vector3d lv = player.getLookAngle();
Direction facing = Direction.getFacingFromVector((float)lv.x, (float)lv.y, (float)lv.z); Direction facing = Direction.getNearest((float)lv.x, (float)lv.y, (float)lv.z);
if((facing != Direction.UP) && (facing != Direction.DOWN)) return; if((facing != Direction.UP) && (facing != Direction.DOWN)) return;
if(state.getBlock() != this) return; if(state.getBlock() != this) return;
SlabType type = state.get(TYPE); SlabType type = state.getValue(TYPE);
if(facing == Direction.DOWN) { if(facing == Direction.DOWN) {
if(type == SlabType.DOUBLE) { if(type == SlabType.DOUBLE) {
world.setBlockState(pos, state.with(TYPE, SlabType.BOTTOM), 3); world.setBlock(pos, state.setValue(TYPE, SlabType.BOTTOM), 3);
} else { } else {
world.removeBlock(pos, false); world.removeBlock(pos, false);
} }
} else if(facing == Direction.UP) { } else if(facing == Direction.UP) {
if(type == SlabType.DOUBLE) { if(type == SlabType.DOUBLE) {
world.setBlockState(pos, state.with(TYPE, SlabType.TOP), 3); world.setBlock(pos, state.setValue(TYPE, SlabType.TOP), 3);
} else { } else {
world.removeBlock(pos, false); world.removeBlock(pos, false);
} }
} }
if(!player.isCreative()) { if(!player.isCreative()) {
stack.grow(1); stack.grow(1);
if(player.inventory != null) player.inventory.markDirty(); if(player.inventory != null) player.inventory.setChanged();
} }
SoundType st = this.getSoundType(state, world, pos, null); SoundType st = this.getSoundType(state, world, pos, null);
world.playSound(player, pos, st.getPlaceSound(), SoundCategory.BLOCKS, (st.getVolume()+1f)/2.5f, 0.9f*st.getPitch()); world.playSound(player, pos, st.getPlaceSound(), SoundCategory.BLOCKS, (st.getVolume()+1f)/2.5f, 0.9f*st.getPitch());
} }
@Override @Override
public boolean receiveFluid(IWorld world, BlockPos pos, BlockState state, FluidState fluidState) public boolean placeLiquid(IWorld world, BlockPos pos, BlockState state, FluidState fluidState)
{ return (state.get(TYPE)==SlabType.DOUBLE) ? false : super.receiveFluid(world, pos, state, fluidState); } { return (state.getValue(TYPE)==SlabType.DOUBLE) ? false : super.placeLiquid(world, pos, state, fluidState); }
@Override @Override
public boolean canContainFluid(IBlockReader world, BlockPos pos, BlockState state, Fluid fluid) public boolean canPlaceLiquid(IBlockReader world, BlockPos pos, BlockState state, Fluid fluid)
{ return (state.get(TYPE)==SlabType.DOUBLE) ? false : super.canContainFluid(world, pos, state, fluid); } { return (state.getValue(TYPE)==SlabType.DOUBLE) ? false : super.canPlaceLiquid(world, pos, state, fluid); }
} }

View file

@ -44,17 +44,17 @@ import java.util.Map;
public class VariantWallBlock extends WallBlock implements StandardBlocks.IStandardBlock public class VariantWallBlock extends WallBlock implements StandardBlocks.IStandardBlock
{ {
public static final BooleanProperty UP = BlockStateProperties.UP; public static final BooleanProperty UP = BlockStateProperties.UP;
public static final EnumProperty<WallHeight> WALL_EAST = BlockStateProperties.WALL_HEIGHT_EAST; public static final EnumProperty<WallHeight> WALL_EAST = BlockStateProperties.EAST_WALL;
public static final EnumProperty<WallHeight> WALL_NORTH = BlockStateProperties.WALL_HEIGHT_NORTH; public static final EnumProperty<WallHeight> WALL_NORTH = BlockStateProperties.NORTH_WALL;
public static final EnumProperty<WallHeight> WALL_SOUTH = BlockStateProperties.WALL_HEIGHT_SOUTH; public static final EnumProperty<WallHeight> WALL_SOUTH = BlockStateProperties.SOUTH_WALL;
public static final EnumProperty<WallHeight> WALL_WEST = BlockStateProperties.WALL_HEIGHT_WEST; public static final EnumProperty<WallHeight> WALL_WEST = BlockStateProperties.WEST_WALL;
public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
public static final IntegerProperty TEXTURE_VARIANT = IntegerProperty.create("tvariant", 0, 7); public static final IntegerProperty TEXTURE_VARIANT = IntegerProperty.create("tvariant", 0, 7);
private final Map<BlockState, VoxelShape> shape_voxels; private final Map<BlockState, VoxelShape> shape_voxels;
private final Map<BlockState, VoxelShape> collision_shape_voxels; private final Map<BlockState, VoxelShape> collision_shape_voxels;
private final long config; private final long config;
public VariantWallBlock(long config, Block.Properties builder) public VariantWallBlock(long config, AbstractBlock.Properties builder)
{ {
super(builder); super(builder);
shape_voxels = buildWallShapes(4, 16, 4, 0, 16, 16); shape_voxels = buildWallShapes(4, 16, 4, 0, 16, 16);
@ -68,7 +68,7 @@ public class VariantWallBlock extends WallBlock implements StandardBlocks.IStand
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag) public void appendHoverText(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag)
{ Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); } { Auxiliaries.Tooltip.addInformation(stack, world, tooltip, flag, true); }
private static VoxelShape combinedShape(VoxelShape pole, WallHeight height, VoxelShape low, VoxelShape high) private static VoxelShape combinedShape(VoxelShape pole, WallHeight height, VoxelShape low, VoxelShape high)
@ -81,36 +81,36 @@ public class VariantWallBlock extends WallBlock implements StandardBlocks.IStand
protected Map<BlockState, VoxelShape> buildWallShapes(double pole_width, double pole_height, double side_width, double side_min_y, double side_max_low_y, double side_max_tall_y) protected Map<BlockState, VoxelShape> buildWallShapes(double pole_width, double pole_height, double side_width, double side_min_y, double side_max_low_y, double side_max_tall_y)
{ {
final double px0=8.0-pole_width, px1=8.0+pole_width, sx0=8.0-side_width, sx1=8.0+side_width; final double px0=8.0-pole_width, px1=8.0+pole_width, sx0=8.0-side_width, sx1=8.0+side_width;
VoxelShape vp = Block.makeCuboidShape(px0, 0, px0, px1, pole_height, px1); VoxelShape vp = Block.box(px0, 0, px0, px1, pole_height, px1);
VoxelShape vs1 = Block.makeCuboidShape(sx0, side_min_y, 0, sx1, side_max_low_y, sx1); VoxelShape vs1 = Block.box(sx0, side_min_y, 0, sx1, side_max_low_y, sx1);
VoxelShape vs2 = Block.makeCuboidShape(sx0, side_min_y, sx0, sx1, side_max_low_y, 16); VoxelShape vs2 = Block.box(sx0, side_min_y, sx0, sx1, side_max_low_y, 16);
VoxelShape vs3 = Block.makeCuboidShape(0, side_min_y, sx0, sx1, side_max_low_y, sx1); VoxelShape vs3 = Block.box(0, side_min_y, sx0, sx1, side_max_low_y, sx1);
VoxelShape vs4 = Block.makeCuboidShape(sx0, side_min_y, sx0, 16, side_max_low_y, sx1); VoxelShape vs4 = Block.box(sx0, side_min_y, sx0, 16, side_max_low_y, sx1);
VoxelShape vs5 = Block.makeCuboidShape(sx0, side_min_y, 0, sx1, side_max_tall_y, sx1); VoxelShape vs5 = Block.box(sx0, side_min_y, 0, sx1, side_max_tall_y, sx1);
VoxelShape vs6 = Block.makeCuboidShape(sx0, side_min_y, sx0, sx1, side_max_tall_y, 16); VoxelShape vs6 = Block.box(sx0, side_min_y, sx0, sx1, side_max_tall_y, 16);
VoxelShape vs7 = Block.makeCuboidShape(0, side_min_y, sx0, sx1, side_max_tall_y, sx1); VoxelShape vs7 = Block.box(0, side_min_y, sx0, sx1, side_max_tall_y, sx1);
VoxelShape vs8 = Block.makeCuboidShape(sx0, side_min_y, sx0, 16, side_max_tall_y, sx1); VoxelShape vs8 = Block.box(sx0, side_min_y, sx0, 16, side_max_tall_y, sx1);
Builder<BlockState, VoxelShape> builder = ImmutableMap.builder(); Builder<BlockState, VoxelShape> builder = ImmutableMap.builder();
for(Boolean up : UP.getAllowedValues()) { for(Boolean up : UP.getPossibleValues()) {
for(WallHeight wh_east : WALL_EAST.getAllowedValues()) { for(WallHeight wh_east : WALL_EAST.getPossibleValues()) {
for(WallHeight wh_north : WALL_NORTH.getAllowedValues()) { for(WallHeight wh_north : WALL_NORTH.getPossibleValues()) {
for(WallHeight wh_west : WALL_WEST.getAllowedValues()) { for(WallHeight wh_west : WALL_WEST.getPossibleValues()) {
for(WallHeight wh_south : WALL_SOUTH.getAllowedValues()) { for(WallHeight wh_south : WALL_SOUTH.getPossibleValues()) {
VoxelShape shape = VoxelShapes.empty(); VoxelShape shape = VoxelShapes.empty();
shape = combinedShape(shape, wh_east, vs4, vs8); shape = combinedShape(shape, wh_east, vs4, vs8);
shape = combinedShape(shape, wh_west, vs3, vs7); shape = combinedShape(shape, wh_west, vs3, vs7);
shape = combinedShape(shape, wh_north, vs1, vs5); shape = combinedShape(shape, wh_north, vs1, vs5);
shape = combinedShape(shape, wh_south, vs2, vs6); shape = combinedShape(shape, wh_south, vs2, vs6);
if(up) shape = VoxelShapes.or(shape, vp); if(up) shape = VoxelShapes.or(shape, vp);
BlockState bs = getDefaultState().with(UP, up) BlockState bs = defaultBlockState().setValue(UP, up)
.with(WALL_EAST, wh_east) .setValue(WALL_EAST, wh_east)
.with(WALL_NORTH, wh_north) .setValue(WALL_NORTH, wh_north)
.with(WALL_WEST, wh_west) .setValue(WALL_WEST, wh_west)
.with(WALL_SOUTH, wh_south); .setValue(WALL_SOUTH, wh_south);
final VoxelShape tvs = shape; final VoxelShape tvs = shape;
TEXTURE_VARIANT.getAllowedValues().forEach((tv)->{ TEXTURE_VARIANT.getPossibleValues().forEach((tv)->{
builder.put(bs.with(TEXTURE_VARIANT, tv).with(WATERLOGGED, false), tvs); builder.put(bs.setValue(TEXTURE_VARIANT, tv).setValue(WATERLOGGED, false), tvs);
builder.put(bs.with(TEXTURE_VARIANT, tv).with(WATERLOGGED, true), tvs); builder.put(bs.setValue(TEXTURE_VARIANT, tv).setValue(WATERLOGGED, true), tvs);
}); });
} }
} }
@ -122,23 +122,23 @@ public class VariantWallBlock extends WallBlock implements StandardBlocks.IStand
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return shape_voxels.getOrDefault(state, VoxelShapes.fullCube()); } { return shape_voxels.getOrDefault(state, VoxelShapes.block()); }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext) public VoxelShape getCollisionShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext selectionContext)
{ return collision_shape_voxels.getOrDefault(state, VoxelShapes.fullCube()); } { return collision_shape_voxels.getOrDefault(state, VoxelShapes.block()); }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder)
{ super.fillStateContainer(builder); builder.add(TEXTURE_VARIANT); } { super.createBlockStateDefinition(builder); builder.add(TEXTURE_VARIANT); }
protected boolean attachesTo(BlockState facingState, IWorldReader world, BlockPos facingPos, Direction side) protected boolean attachesTo(BlockState facingState, IWorldReader world, BlockPos facingPos, Direction side)
{ {
final Block block = facingState.getBlock(); final Block block = facingState.getBlock();
if((block instanceof FenceGateBlock) || (block instanceof WallBlock)) return true; if((block instanceof FenceGateBlock) || (block instanceof WallBlock)) return true;
final BlockState oppositeState = world.getBlockState(facingPos.offset(side, 2)); final BlockState oppositeState = world.getBlockState(facingPos.relative(side, 2));
if(!(oppositeState.getBlock() instanceof VariantWallBlock)) return false; if(!(oppositeState.getBlock() instanceof VariantWallBlock)) return false;
return facingState.isNormalCube(world, facingPos) && Block.hasEnoughSolidSide(world, facingPos, side); return facingState.isRedstoneConductor(world, facingPos) && Block.canSupportCenter(world, facingPos, side);
} }
protected WallHeight selectWallHeight(IWorldReader world, BlockPos pos, Direction direction) protected WallHeight selectWallHeight(IWorldReader world, BlockPos pos, Direction direction)
@ -148,38 +148,38 @@ public class VariantWallBlock extends WallBlock implements StandardBlocks.IStand
public BlockState getStateForPlacement(BlockItemUseContext context) public BlockState getStateForPlacement(BlockItemUseContext context)
{ {
IWorldReader world = context.getWorld(); IWorldReader world = context.getLevel();
BlockPos pos = context.getPos(); BlockPos pos = context.getClickedPos();
FluidState fs = context.getWorld().getFluidState(context.getPos()); FluidState fs = context.getLevel().getFluidState(context.getClickedPos());
boolean n = attachesTo(world.getBlockState(pos.north()), world, pos.north(), Direction.SOUTH); boolean n = attachesTo(world.getBlockState(pos.north()), world, pos.north(), Direction.SOUTH);
boolean e = attachesTo(world.getBlockState(pos.east()), world, pos.east(), Direction.WEST); boolean e = attachesTo(world.getBlockState(pos.east()), world, pos.east(), Direction.WEST);
boolean s = attachesTo(world.getBlockState(pos.south()), world, pos.south(), Direction.NORTH); boolean s = attachesTo(world.getBlockState(pos.south()), world, pos.south(), Direction.NORTH);
boolean w = attachesTo(world.getBlockState(pos.west()), world, pos.west(), Direction.EAST); boolean w = attachesTo(world.getBlockState(pos.west()), world, pos.west(), Direction.EAST);
boolean not_straight = (!n || !s || e || w) && (n || s || !e || !w); boolean not_straight = (!n || !s || e || w) && (n || s || !e || !w);
return getDefaultState().with(UP, not_straight) return defaultBlockState().setValue(UP, not_straight)
.with(WALL_NORTH, n ? selectWallHeight(world, pos, Direction.NORTH) : WallHeight.NONE) .setValue(WALL_NORTH, n ? selectWallHeight(world, pos, Direction.NORTH) : WallHeight.NONE)
.with(WALL_EAST , e ? selectWallHeight(world, pos, Direction.EAST) : WallHeight.NONE) .setValue(WALL_EAST , e ? selectWallHeight(world, pos, Direction.EAST) : WallHeight.NONE)
.with(WALL_SOUTH, s ? selectWallHeight(world, pos, Direction.SOUTH) : WallHeight.NONE) .setValue(WALL_SOUTH, s ? selectWallHeight(world, pos, Direction.SOUTH) : WallHeight.NONE)
.with(WALL_WEST , w ? selectWallHeight(world, pos, Direction.WEST) : WallHeight.NONE) .setValue(WALL_WEST , w ? selectWallHeight(world, pos, Direction.WEST) : WallHeight.NONE)
.with(WATERLOGGED, fs.getFluid()==Fluids.WATER); .setValue(WATERLOGGED, fs.getType()==Fluids.WATER);
} }
@Override @Override
public BlockState updatePostPlacement(BlockState state, Direction side, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos) public BlockState updateShape(BlockState state, Direction side, BlockState facingState, IWorld world, BlockPos pos, BlockPos facingPos)
{ {
if(state.get(WATERLOGGED)) world.getPendingFluidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickRate(world)); if(state.getValue(WATERLOGGED)) world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world));
if(side == Direction.DOWN) return super.updatePostPlacement(state, side, facingState, world, pos, facingPos); if(side == Direction.DOWN) return super.updateShape(state, side, facingState, world, pos, facingPos);
boolean n = (side==Direction.NORTH) ? this.attachesTo(facingState, world, facingPos, side) : state.get(WALL_NORTH)!=WallHeight.NONE; boolean n = (side==Direction.NORTH) ? this.attachesTo(facingState, world, facingPos, side) : state.getValue(WALL_NORTH)!=WallHeight.NONE;
boolean e = (side==Direction.EAST) ? this.attachesTo(facingState, world, facingPos, side) : state.get(WALL_EAST)!=WallHeight.NONE; boolean e = (side==Direction.EAST) ? this.attachesTo(facingState, world, facingPos, side) : state.getValue(WALL_EAST)!=WallHeight.NONE;
boolean s = (side==Direction.SOUTH) ? this.attachesTo(facingState, world, facingPos, side) : state.get(WALL_SOUTH)!=WallHeight.NONE; boolean s = (side==Direction.SOUTH) ? this.attachesTo(facingState, world, facingPos, side) : state.getValue(WALL_SOUTH)!=WallHeight.NONE;
boolean w = (side==Direction.WEST) ? this.attachesTo(facingState, world, facingPos, side) : state.get(WALL_WEST)!=WallHeight.NONE; boolean w = (side==Direction.WEST) ? this.attachesTo(facingState, world, facingPos, side) : state.getValue(WALL_WEST)!=WallHeight.NONE;
boolean not_straight = (!n || !s || e || w) && (n || s || !e || !w); boolean not_straight = (!n || !s || e || w) && (n || s || !e || !w);
return state.with(UP, not_straight) return state.setValue(UP, not_straight)
.with(WALL_NORTH, n ? selectWallHeight(world, pos, Direction.NORTH) : WallHeight.NONE) .setValue(WALL_NORTH, n ? selectWallHeight(world, pos, Direction.NORTH) : WallHeight.NONE)
.with(WALL_EAST , e ? selectWallHeight(world, pos, Direction.EAST) : WallHeight.NONE) .setValue(WALL_EAST , e ? selectWallHeight(world, pos, Direction.EAST) : WallHeight.NONE)
.with(WALL_SOUTH, s ? selectWallHeight(world, pos, Direction.SOUTH) : WallHeight.NONE) .setValue(WALL_SOUTH, s ? selectWallHeight(world, pos, Direction.SOUTH) : WallHeight.NONE)
.with(WALL_WEST , w ? selectWallHeight(world, pos, Direction.WEST) : WallHeight.NONE) .setValue(WALL_WEST , w ? selectWallHeight(world, pos, Direction.WEST) : WallHeight.NONE)
.with(TEXTURE_VARIANT, ((int)MathHelper.getPositionRandom(pos)) & 0x7); .setValue(TEXTURE_VARIANT, ((int)MathHelper.getSeed(pos)) & 0x7);
} }
@Override @Override
@ -187,11 +187,11 @@ public class VariantWallBlock extends WallBlock implements StandardBlocks.IStand
{ return false; } { return false; }
@Override @Override
public boolean canSpawnInBlock() public boolean isPossibleToRespawnInThis()
{ return false; } { return false; }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public PushReaction getPushReaction(BlockState state) public PushReaction getPistonPushReaction(BlockState state)
{ return PushReaction.NORMAL; } { return PushReaction.NORMAL; }
} }

View file

@ -24,14 +24,14 @@ public abstract class ContainerGui<T extends Container> extends ContainerScreen<
{ {
this.minecraft = minecraft; this.minecraft = minecraft;
this.itemRenderer = minecraft.getItemRenderer(); this.itemRenderer = minecraft.getItemRenderer();
this.font = minecraft.fontRenderer; this.font = minecraft.font;
this.width = width; this.width = width;
this.height = height; this.height = height;
java.util.function.Consumer<Widget> remove = (b) -> { buttons.remove(b); children.remove(b); }; java.util.function.Consumer<Widget> remove = (b) -> { buttons.remove(b); children.remove(b); };
if((!canHaveDisturbingButtonsFromOtherMods()) || (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent.Pre(this, this.buttons, this::addButton, remove)))) { if((!canHaveDisturbingButtonsFromOtherMods()) || (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent.Pre(this, this.buttons, this::addButton, remove)))) {
this.buttons.clear(); this.buttons.clear();
this.children.clear(); this.children.clear();
this.setListener((IGuiEventListener)null); this.setFocused((IGuiEventListener)null);
this.init(); this.init();
} }
if(canHaveDisturbingButtonsFromOtherMods()) { if(canHaveDisturbingButtonsFromOtherMods()) {

View file

@ -47,7 +47,7 @@ public class LootTableGen extends LootTableProvider
{ return Auxiliaries.modid() + " Loot Tables"; } { return Auxiliaries.modid() + " Loot Tables"; }
@Override @Override
public void act(DirectoryCache cache) public void run(DirectoryCache cache)
{ save(cache, generate()); } { save(cache, generate()); }
//-------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------
@ -62,7 +62,7 @@ public class LootTableGen extends LootTableProvider
tables.put( tables.put(
block.getLootTable(), block.getLootTable(),
defaultBlockDrops(block.getRegistryName().getPath() + "_dlt", block) defaultBlockDrops(block.getRegistryName().getPath() + "_dlt", block)
.setParameterSet(LootParameterSets.BLOCK).build()); .setParamSet(LootParameterSets.BLOCK).build());
} else { } else {
LOGGER.info("Dynamic drop list, skipping loot table for " + block.getRegistryName()); LOGGER.info("Dynamic drop list, skipping loot table for " + block.getRegistryName());
} }
@ -76,7 +76,7 @@ public class LootTableGen extends LootTableProvider
tables.forEach((rl,tab)->{ tables.forEach((rl,tab)->{
Path fp = root.resolve("data/" + rl.getNamespace() + "/loot_tables/" + rl.getPath() + ".json"); Path fp = root.resolve("data/" + rl.getNamespace() + "/loot_tables/" + rl.getPath() + ".json");
try { try {
IDataProvider.save(GSON, cache, LootTableManager.toJson(tab), fp); IDataProvider.save(GSON, cache, LootTableManager.serialize(tab), fp);
} catch(Exception e) { } catch(Exception e) {
LOGGER.error("Failed to save loottable '"+fp+"', exception: " + e); LOGGER.error("Failed to save loottable '"+fp+"', exception: " + e);
} }
@ -85,12 +85,12 @@ public class LootTableGen extends LootTableProvider
private LootTable.Builder defaultBlockDrops(String rl_path, Block block) private LootTable.Builder defaultBlockDrops(String rl_path, Block block)
{ {
ItemLootEntry.Builder iltb = ItemLootEntry.builder(block); StandaloneLootEntry.Builder iltb = ItemLootEntry.lootTableItem(block);
iltb.acceptFunction(CopyName.builder(Source.BLOCK_ENTITY)); iltb.apply(CopyName.copyName(Source.BLOCK_ENTITY));
if(block.hasTileEntity(block.getDefaultState())) { if(block.hasTileEntity(block.defaultBlockState())) {
iltb.acceptFunction(CopyNbt.builder(CopyNbt.Source.BLOCK_ENTITY)); iltb.apply(CopyNbt.copyData(CopyNbt.Source.BLOCK_ENTITY));
} }
return LootTable.builder().addLootPool(LootPool.builder().name(rl_path).rolls(ConstantRange.of(1)).addEntry(iltb)); return LootTable.lootTable().withPool(LootPool.lootPool().name(rl_path).setRolls(ConstantRange.exactly(1)).add(iltb));
} }
} }

View file

@ -78,20 +78,20 @@ public class Auxiliaries
{ return ModList.get().isLoaded(registry_name); } { return ModList.get().isLoaded(registry_name); }
public static final boolean isDevelopmentMode() public static final boolean isDevelopmentMode()
{ return SharedConstants.developmentMode; } { return SharedConstants.IS_RUNNING_IN_IDE; }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public static final boolean isShiftDown() public static final boolean isShiftDown()
{ {
return (InputMappings.isKeyDown(SidedProxy.mc().getMainWindow().getHandle(), GLFW.GLFW_KEY_LEFT_SHIFT) || return (InputMappings.isKeyDown(SidedProxy.mc().getWindow().getWindow(), GLFW.GLFW_KEY_LEFT_SHIFT) ||
InputMappings.isKeyDown(SidedProxy.mc().getMainWindow().getHandle(), GLFW.GLFW_KEY_RIGHT_SHIFT)); InputMappings.isKeyDown(SidedProxy.mc().getWindow().getWindow(), GLFW.GLFW_KEY_RIGHT_SHIFT));
} }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public static final boolean isCtrlDown() public static final boolean isCtrlDown()
{ {
return (InputMappings.isKeyDown(SidedProxy.mc().getMainWindow().getHandle(), GLFW.GLFW_KEY_LEFT_CONTROL) || return (InputMappings.isKeyDown(SidedProxy.mc().getWindow().getWindow(), GLFW.GLFW_KEY_LEFT_CONTROL) ||
InputMappings.isKeyDown(SidedProxy.mc().getMainWindow().getHandle(), GLFW.GLFW_KEY_RIGHT_CONTROL)); InputMappings.isKeyDown(SidedProxy.mc().getWindow().getWindow(), GLFW.GLFW_KEY_RIGHT_CONTROL));
} }
// ------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------
@ -133,7 +133,7 @@ public class Auxiliaries
public static String localize(String translationKey, Object... args) public static String localize(String translationKey, Object... args)
{ {
TranslationTextComponent tr = new TranslationTextComponent(translationKey, args); TranslationTextComponent tr = new TranslationTextComponent(translationKey, args);
tr.mergeStyle(TextFormatting.RESET); tr.withStyle(TextFormatting.RESET);
final String ft = tr.getString(); final String ft = tr.getString();
if(ft.contains("${")) { if(ft.contains("${")) {
// Non-recursive, non-argument lang file entry cross referencing. // Non-recursive, non-argument lang file entry cross referencing.
@ -170,7 +170,7 @@ public class Auxiliaries
*/ */
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public static boolean hasTranslation(String key) public static boolean hasTranslation(String key)
{ return net.minecraft.client.resources.I18n.hasKey(key); } { return net.minecraft.client.resources.I18n.exists(key); }
public static final class Tooltip public static final class Tooltip
{ {
@ -206,7 +206,7 @@ public class Auxiliaries
if(tip_text.isEmpty()) return false; if(tip_text.isEmpty()) return false;
String[] tip_list = tip_text.split("\\r?\\n"); String[] tip_list = tip_text.split("\\r?\\n");
for(String tip:tip_list) { for(String tip:tip_list) {
tooltip.add(new StringTextComponent(tip.replaceAll("\\s+$","").replaceAll("^\\s+", "")).mergeStyle(TextFormatting.GRAY)); tooltip.add(new StringTextComponent(tip.replaceAll("\\s+$","").replaceAll("^\\s+", "")).withStyle(TextFormatting.GRAY));
} }
return true; return true;
} }
@ -218,13 +218,13 @@ public class Auxiliaries
*/ */
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public static boolean addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag, boolean addAdvancedTooltipHints) public static boolean addInformation(ItemStack stack, @Nullable IBlockReader world, List<ITextComponent> tooltip, ITooltipFlag flag, boolean addAdvancedTooltipHints)
{ return addInformation(stack.getTranslationKey(), stack.getTranslationKey(), tooltip, flag, addAdvancedTooltipHints); } { return addInformation(stack.getDescriptionId(), stack.getDescriptionId(), tooltip, flag, addAdvancedTooltipHints); }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public static boolean addInformation(String translation_key, List<ITextComponent> tooltip) public static boolean addInformation(String translation_key, List<ITextComponent> tooltip)
{ {
if(!Auxiliaries.hasTranslation(translation_key)) return false; if(!Auxiliaries.hasTranslation(translation_key)) return false;
tooltip.add(new StringTextComponent(localize(translation_key).replaceAll("\\s+$","").replaceAll("^\\s+", "")).mergeStyle(TextFormatting.GRAY)); tooltip.add(new StringTextComponent(localize(translation_key).replaceAll("\\s+$","").replaceAll("^\\s+", "")).withStyle(TextFormatting.GRAY));
return true; return true;
} }
@ -238,7 +238,7 @@ public class Auxiliaries
} }
public static @Nullable ITextComponent unserializeTextComponent(String serialized) public static @Nullable ITextComponent unserializeTextComponent(String serialized)
{ return ITextComponent.Serializer.getComponentFromJson(serialized); } { return ITextComponent.Serializer.fromJson(serialized); }
public static String serializeTextComponent(ITextComponent tc) public static String serializeTextComponent(ITextComponent tc)
{ return (tc==null) ? ("") : (ITextComponent.Serializer.toJson(tc)); } { return (tc==null) ? ("") : (ITextComponent.Serializer.toJson(tc)); }
@ -252,7 +252,7 @@ public class Auxiliaries
*/ */
public static @Nullable ITextComponent getItemLabel(ItemStack stack) public static @Nullable ITextComponent getItemLabel(ItemStack stack)
{ {
CompoundNBT nbt = stack.getChildTag("display"); CompoundNBT nbt = stack.getTagElement("display");
if(nbt != null && nbt.contains("Name", 8)) { if(nbt != null && nbt.contains("Name", 8)) {
try { try {
ITextComponent tc = unserializeTextComponent(nbt.getString("Name")); ITextComponent tc = unserializeTextComponent(nbt.getString("Name"));
@ -268,10 +268,10 @@ public class Auxiliaries
public static ItemStack setItemLabel(ItemStack stack, @Nullable ITextComponent name) public static ItemStack setItemLabel(ItemStack stack, @Nullable ITextComponent name)
{ {
if(name != null) { if(name != null) {
CompoundNBT nbt = stack.getOrCreateChildTag("display"); CompoundNBT nbt = stack.getOrCreateTagElement("display");
nbt.putString("Name", serializeTextComponent(name)); nbt.putString("Name", serializeTextComponent(name));
} else { } else {
if(stack.hasTag()) stack.removeChildTag("display"); if(stack.hasTag()) stack.removeTagKey("display");
} }
return stack; return stack;
} }
@ -286,7 +286,7 @@ public class Auxiliaries
public static final AxisAlignedBB getRotatedAABB(AxisAlignedBB bb, Direction new_facing, boolean horizontal_rotation) public static final AxisAlignedBB getRotatedAABB(AxisAlignedBB bb, Direction new_facing, boolean horizontal_rotation)
{ {
if(!horizontal_rotation) { if(!horizontal_rotation) {
switch(new_facing.getIndex()) { switch(new_facing.get3DDataValue()) {
case 0: return new AxisAlignedBB(1-bb.maxX, bb.minZ, bb.minY, 1-bb.minX, bb.maxZ, bb.maxY); // D case 0: return new AxisAlignedBB(1-bb.maxX, bb.minZ, bb.minY, 1-bb.minX, bb.maxZ, bb.maxY); // D
case 1: return new AxisAlignedBB(1-bb.maxX, 1-bb.maxZ, 1-bb.maxY, 1-bb.minX, 1-bb.minZ, 1-bb.minY); // U case 1: return new AxisAlignedBB(1-bb.maxX, 1-bb.maxZ, 1-bb.maxY, 1-bb.minX, 1-bb.minZ, 1-bb.minY); // U
case 2: return new AxisAlignedBB( bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); // N --> bb case 2: return new AxisAlignedBB( bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); // N --> bb
@ -295,7 +295,7 @@ public class Auxiliaries
case 5: return new AxisAlignedBB(1-bb.maxZ, bb.minY, bb.minX, 1-bb.minZ, bb.maxY, bb.maxX); // E case 5: return new AxisAlignedBB(1-bb.maxZ, bb.minY, bb.minX, 1-bb.minZ, bb.maxY, bb.maxX); // E
} }
} else { } else {
switch(new_facing.getIndex()) { switch(new_facing.get3DDataValue()) {
case 0: return new AxisAlignedBB( bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); // D --> bb case 0: return new AxisAlignedBB( bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); // D --> bb
case 1: return new AxisAlignedBB( bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); // U --> bb case 1: return new AxisAlignedBB( bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); // U --> bb
case 2: return new AxisAlignedBB( bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); // N --> bb case 2: return new AxisAlignedBB( bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); // N --> bb
@ -347,7 +347,7 @@ public class Auxiliaries
public static final VoxelShape getUnionShape(AxisAlignedBB ... aabbs) public static final VoxelShape getUnionShape(AxisAlignedBB ... aabbs)
{ {
VoxelShape shape = VoxelShapes.empty(); VoxelShape shape = VoxelShapes.empty();
for(AxisAlignedBB aabb: aabbs) shape = VoxelShapes.combineAndSimplify(shape, VoxelShapes.create(aabb), IBooleanFunction.OR); for(AxisAlignedBB aabb: aabbs) shape = VoxelShapes.join(shape, VoxelShapes.create(aabb), IBooleanFunction.OR);
return shape; return shape;
} }
@ -355,7 +355,7 @@ public class Auxiliaries
{ {
VoxelShape shape = VoxelShapes.empty(); VoxelShape shape = VoxelShapes.empty();
for(AxisAlignedBB[] aabbs:aabb_list) { for(AxisAlignedBB[] aabbs:aabb_list) {
for(AxisAlignedBB aabb: aabbs) shape = VoxelShapes.combine(shape, VoxelShapes.create(aabb), IBooleanFunction.OR); for(AxisAlignedBB aabb: aabbs) shape = VoxelShapes.joinUnoptimized(shape, VoxelShapes.create(aabb), IBooleanFunction.OR);
} }
return shape; return shape;
} }

View file

@ -233,8 +233,8 @@ public class Fluidics
*/ */
public static @Nullable Tuple<Fluid, Integer> manualTrackedFluidHandlerInteraction(World world, BlockPos pos, @Nullable Direction side, PlayerEntity player, Hand hand) public static @Nullable Tuple<Fluid, Integer> manualTrackedFluidHandlerInteraction(World world, BlockPos pos, @Nullable Direction side, PlayerEntity player, Hand hand)
{ {
if(world.isRemote()) return null; if(world.isClientSide()) return null;
final ItemStack held = player.getHeldItem(hand); final ItemStack held = player.getItemInHand(hand);
if(held.isEmpty()) return null; if(held.isEmpty()) return null;
final IFluidHandler fh = FluidUtil.getFluidHandler(world, pos, side).orElse(null); final IFluidHandler fh = FluidUtil.getFluidHandler(world, pos, side).orElse(null);
if(fh==null) return null; if(fh==null) return null;
@ -244,7 +244,7 @@ public class Fluidics
if(!far.isSuccess()) far = FluidUtil.tryEmptyContainerAndStow(held, fh, ih, Integer.MAX_VALUE, player, true); if(!far.isSuccess()) far = FluidUtil.tryEmptyContainerAndStow(held, fh, ih, Integer.MAX_VALUE, player, true);
if(!far.isSuccess()) return null; if(!far.isSuccess()) return null;
final ItemStack rstack = far.getResult().copy(); final ItemStack rstack = far.getResult().copy();
player.setHeldItem(hand, far.getResult()); player.setItemInHand(hand, far.getResult());
final IFluidHandler fh_before = FluidUtil.getFluidHandler(held).orElse(null); final IFluidHandler fh_before = FluidUtil.getFluidHandler(held).orElse(null);
final IFluidHandler fh_after = FluidUtil.getFluidHandler(rstack).orElse(null); final IFluidHandler fh_after = FluidUtil.getFluidHandler(rstack).orElse(null);
if((fh_before==null) || (fh_after==null) || (fh_after.getTanks()!=fh_before.getTanks())) return null; // should not be, but y'never know. if((fh_before==null) || (fh_after==null) || (fh_after.getTanks()!=fh_before.getTanks())) return null; // should not be, but y'never know.

View file

@ -44,14 +44,14 @@ import java.util.stream.Stream;
public class Inventories public class Inventories
{ {
public static boolean areItemStacksIdentical(ItemStack a, ItemStack b) public static boolean areItemStacksIdentical(ItemStack a, ItemStack b)
{ return (a.getItem()==b.getItem()) && ItemStack.areItemStackTagsEqual(a, b); } { return (a.getItem()==b.getItem()) && ItemStack.tagMatches(a, b); }
public static boolean areItemStacksDifferent(ItemStack a, ItemStack b) public static boolean areItemStacksDifferent(ItemStack a, ItemStack b)
{ return (a.getItem()!=b.getItem()) || (!ItemStack.areItemStackTagsEqual(a, b)); } { return (a.getItem()!=b.getItem()) || (!ItemStack.tagMatches(a, b)); }
public static IItemHandler itemhandler(World world, BlockPos pos, @Nullable Direction side) public static IItemHandler itemhandler(World world, BlockPos pos, @Nullable Direction side)
{ {
TileEntity te = world.getTileEntity(pos); TileEntity te = world.getBlockEntity(pos);
if(te==null) return null; if(te==null) return null;
IItemHandler ih = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side).orElse(null); IItemHandler ih = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side).orElse(null);
if(ih!=null) return ih; if(ih!=null) return ih;
@ -84,7 +84,7 @@ public class Inventories
} }
public static ItemStack insert(World world, BlockPos pos, @Nullable Direction side, ItemStack stack, boolean simulate) public static ItemStack insert(World world, BlockPos pos, @Nullable Direction side, ItemStack stack, boolean simulate)
{ return insert(world.getTileEntity(pos), side, stack, simulate); } { return insert(world.getBlockEntity(pos), side, stack, simulate); }
public static ItemStack extract(@Nullable IItemHandler inventory, @Nullable ItemStack match, int amount, boolean simulate) public static ItemStack extract(@Nullable IItemHandler inventory, @Nullable ItemStack match, int amount, boolean simulate)
{ {
@ -125,16 +125,16 @@ public class Inventories
public static class MappedItemHandler implements IItemHandler public static class MappedItemHandler implements IItemHandler
{ {
private BiPredicate<Integer, ItemStack> extraction_predicate_; private final BiPredicate<Integer, ItemStack> extraction_predicate_;
private BiPredicate<Integer, ItemStack> insertion_predicate_; private final BiPredicate<Integer, ItemStack> insertion_predicate_;
private List<Integer> slot_map_; private final List<Integer> slot_map_;
private final IInventory inv_; private final IInventory inv_;
public MappedItemHandler(IInventory inv, List<Integer> slot_map, BiPredicate<Integer, ItemStack> extraction_predicate, BiPredicate<Integer, ItemStack> insertion_predicate) public MappedItemHandler(IInventory inv, List<Integer> slot_map, BiPredicate<Integer, ItemStack> extraction_predicate, BiPredicate<Integer, ItemStack> insertion_predicate)
{ inv_ = inv; extraction_predicate_ = extraction_predicate; insertion_predicate_ = insertion_predicate; slot_map_ = slot_map; } { inv_ = inv; extraction_predicate_ = extraction_predicate; insertion_predicate_ = insertion_predicate; slot_map_ = slot_map; }
public MappedItemHandler(IInventory inv, BiPredicate<Integer, ItemStack> extraction_predicate, BiPredicate<Integer, ItemStack> insertion_predicate) public MappedItemHandler(IInventory inv, BiPredicate<Integer, ItemStack> extraction_predicate, BiPredicate<Integer, ItemStack> insertion_predicate)
{ this(inv, IntStream.range(0, inv.getSizeInventory()).boxed().collect(Collectors.toList()), extraction_predicate, insertion_predicate); } { this(inv, IntStream.range(0, inv.getContainerSize()).boxed().collect(Collectors.toList()), extraction_predicate, insertion_predicate); }
public MappedItemHandler(IInventory inv) public MappedItemHandler(IInventory inv)
{ this(inv, (i,s)->true, (i,s)->true); } { this(inv, (i,s)->true, (i,s)->true); }
@ -156,18 +156,18 @@ public class Inventories
@Override @Override
@Nonnull @Nonnull
public ItemStack getStackInSlot(int slot) public ItemStack getStackInSlot(int slot)
{ return (slot >= slot_map_.size()) ? ItemStack.EMPTY : inv_.getStackInSlot(slot_map_.get(slot)); } { return (slot >= slot_map_.size()) ? ItemStack.EMPTY : inv_.getItem(slot_map_.get(slot)); }
@Override @Override
public int getSlotLimit(int slot) public int getSlotLimit(int slot)
{ return inv_.getInventoryStackLimit(); } { return inv_.getMaxStackSize(); }
@Override @Override
public boolean isItemValid(int slot, @Nonnull ItemStack stack) public boolean isItemValid(int slot, @Nonnull ItemStack stack)
{ {
if(slot >= slot_map_.size()) return false; if(slot >= slot_map_.size()) return false;
slot = slot_map_.get(slot); slot = slot_map_.get(slot);
return insertion_predicate_.test(slot, stack) && inv_.isItemValidForSlot(slot, stack); return insertion_predicate_.test(slot, stack) && inv_.canPlaceItem(slot, stack);
} }
@Override @Override
@ -178,9 +178,9 @@ public class Inventories
if(slot >= slot_map_.size()) return stack; if(slot >= slot_map_.size()) return stack;
slot = slot_map_.get(slot); slot = slot_map_.get(slot);
if(!insertion_predicate_.test(slot, stack)) return stack; if(!insertion_predicate_.test(slot, stack)) return stack;
if(!inv_.isItemValidForSlot(slot, stack)) return stack; if(!inv_.canPlaceItem(slot, stack)) return stack;
ItemStack sst = inv_.getStackInSlot(slot); ItemStack sst = inv_.getItem(slot);
final int slot_limit = inv_.getInventoryStackLimit(); final int slot_limit = inv_.getMaxStackSize();
if(!sst.isEmpty()) { if(!sst.isEmpty()) {
if(sst.getCount() >= Math.min(sst.getMaxStackSize(), slot_limit)) return stack; if(sst.getCount() >= Math.min(sst.getMaxStackSize(), slot_limit)) return stack;
if(!ItemHandlerHelper.canItemStacksStack(stack, sst)) return stack; if(!ItemHandlerHelper.canItemStacksStack(stack, sst)) return stack;
@ -189,8 +189,8 @@ public class Inventories
if(!simulate) { if(!simulate) {
stack = stack.copy(); stack = stack.copy();
stack.grow(sst.getCount()); stack.grow(sst.getCount());
inv_.setInventorySlotContents(slot, stack); inv_.setItem(slot, stack);
inv_.markDirty(); inv_.setChanged();
} }
return ItemStack.EMPTY; return ItemStack.EMPTY;
} else { } else {
@ -200,8 +200,8 @@ public class Inventories
} else { } else {
ItemStack diff = stack.split(limit); ItemStack diff = stack.split(limit);
diff.grow(sst.getCount()); diff.grow(sst.getCount());
inv_.setInventorySlotContents(slot, diff); inv_.setItem(slot, diff);
inv_.markDirty(); inv_.setChanged();
} }
return stack; return stack;
} }
@ -212,14 +212,14 @@ public class Inventories
if(simulate) { if(simulate) {
stack.shrink(limit); stack.shrink(limit);
} else { } else {
inv_.setInventorySlotContents(slot, stack.split(limit)); inv_.setItem(slot, stack.split(limit));
inv_.markDirty(); inv_.setChanged();
} }
return stack; return stack;
} else { } else {
if(!simulate) { if(!simulate) {
inv_.setInventorySlotContents(slot, stack.copy()); inv_.setItem(slot, stack.copy());
inv_.markDirty(); inv_.setChanged();
} }
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
@ -232,14 +232,14 @@ public class Inventories
if(amount <= 0) return ItemStack.EMPTY; if(amount <= 0) return ItemStack.EMPTY;
if(slot >= slot_map_.size()) return ItemStack.EMPTY; if(slot >= slot_map_.size()) return ItemStack.EMPTY;
slot = slot_map_.get(slot); slot = slot_map_.get(slot);
ItemStack stack = inv_.getStackInSlot(slot); ItemStack stack = inv_.getItem(slot);
if(!extraction_predicate_.test(slot, stack)) return ItemStack.EMPTY; if(!extraction_predicate_.test(slot, stack)) return ItemStack.EMPTY;
if(simulate) { if(simulate) {
stack = stack.copy(); stack = stack.copy();
if(amount < stack.getCount()) stack.setCount(amount); if(amount < stack.getCount()) stack.setCount(amount);
} else { } else {
stack = inv_.decrStackSize(slot, Math.min(stack.getCount(), amount)); stack = inv_.removeItem(slot, Math.min(stack.getCount(), amount));
inv_.markDirty(); inv_.setChanged();
} }
return stack; return stack;
} }
@ -294,8 +294,8 @@ public class Inventories
public InventoryRange(IInventory inventory, int offset, int size, int num_rows) public InventoryRange(IInventory inventory, int offset, int size, int num_rows)
{ {
this.inventory = inventory; this.inventory = inventory;
this.offset = MathHelper.clamp(offset, 0, inventory.getSizeInventory()-1); this.offset = MathHelper.clamp(offset, 0, inventory.getContainerSize()-1);
this.size = MathHelper.clamp(size, 0, inventory.getSizeInventory()-this.offset); this.size = MathHelper.clamp(size, 0, inventory.getContainerSize()-this.offset);
this.num_rows = num_rows; this.num_rows = num_rows;
} }
@ -320,62 +320,59 @@ public class Inventories
public InventoryRange setMaxStackSize(int count) public InventoryRange setMaxStackSize(int count)
{ max_stack_size_ = Math.max(count, 1) ; return this; } { max_stack_size_ = Math.max(count, 1) ; return this; }
public int getMaxStackSize()
{ return max_stack_size_ ; }
// IInventory ------------------------------------------------------------------------------------------------------ // IInventory ------------------------------------------------------------------------------------------------------
@Override @Override
public void clear() public void clearContent()
{ inventory.clear(); } { inventory.clearContent(); }
@Override @Override
public int getSizeInventory() public int getContainerSize()
{ return size; } { return size; }
@Override @Override
public boolean isEmpty() public boolean isEmpty()
{ for(int i=0; i<size; ++i) if(!inventory.getStackInSlot(offset+i).isEmpty()){return false;} return true; } { for(int i=0; i<size; ++i) if(!inventory.getItem(offset+i).isEmpty()){return false;} return true; }
@Override @Override
public ItemStack getStackInSlot(int index) public ItemStack getItem(int index)
{ return inventory.getStackInSlot(offset+index); } { return inventory.getItem(offset+index); }
@Override @Override
public ItemStack decrStackSize(int index, int count) public ItemStack removeItem(int index, int count)
{ return inventory.decrStackSize(offset+index, count); } { return inventory.removeItem(offset+index, count); }
@Override @Override
public ItemStack removeStackFromSlot(int index) public ItemStack removeItemNoUpdate(int index)
{ return inventory.removeStackFromSlot(offset+index); } { return inventory.removeItemNoUpdate(offset+index); }
@Override @Override
public void setInventorySlotContents(int index, ItemStack stack) public void setItem(int index, ItemStack stack)
{ inventory.setInventorySlotContents(offset+index, stack); } { inventory.setItem(offset+index, stack); }
@Override @Override
public int getInventoryStackLimit() public int getMaxStackSize()
{ return Math.min(max_stack_size_, inventory.getInventoryStackLimit()); } { return Math.min(max_stack_size_, inventory.getMaxStackSize()); }
@Override @Override
public void markDirty() public void setChanged()
{ inventory.markDirty(); } { inventory.setChanged(); }
@Override @Override
public boolean isUsableByPlayer(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return inventory.isUsableByPlayer(player); } { return inventory.stillValid(player); }
@Override @Override
public void openInventory(PlayerEntity player) public void startOpen(PlayerEntity player)
{ inventory.openInventory(player); } { inventory.startOpen(player); }
@Override @Override
public void closeInventory(PlayerEntity player) public void stopOpen(PlayerEntity player)
{ inventory.closeInventory(player); } { inventory.stopOpen(player); }
@Override @Override
public boolean isItemValidForSlot(int index, ItemStack stack) public boolean canPlaceItem(int index, ItemStack stack)
{ return validator_.test(offset+index, stack) && inventory.isItemValidForSlot(offset+index, stack); } { return validator_.test(offset+index, stack) && inventory.canPlaceItem(offset+index, stack); }
//------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------
@ -386,7 +383,7 @@ public class Inventories
{ {
int n = 0; // ... std::accumulate() the old school way. int n = 0; // ... std::accumulate() the old school way.
for(int i=0; i<size; ++i) { for(int i=0; i<size; ++i) {
if(areItemStacksIdentical(ref_stack, getStackInSlot(i))) ++n; if(areItemStacksIdentical(ref_stack, getItem(i))) ++n;
} }
return n; return n;
} }
@ -395,7 +392,7 @@ public class Inventories
{ {
int n = 0; int n = 0;
for(int i=0; i<size; ++i) { for(int i=0; i<size; ++i) {
ItemStack stack = getStackInSlot(i); ItemStack stack = getItem(i);
if(areItemStacksIdentical(ref_stack, stack)) n += stack.getCount(); if(areItemStacksIdentical(ref_stack, stack)) n += stack.getCount();
} }
return n; return n;
@ -418,7 +415,7 @@ public class Inventories
int num_matches = 0; int num_matches = 0;
for(int i=0; i < size; ++i) { for(int i=0; i < size; ++i) {
final int sno = reverse ? (size-1-i) : (i); final int sno = reverse ? (size-1-i) : (i);
final ItemStack stack = getStackInSlot(sno); final ItemStack stack = getItem(sno);
if(stack.isEmpty()) { if(stack.isEmpty()) {
empties[sno] = true; empties[sno] = true;
} else if(areItemStacksIdentical(stack, mvstack)) { } else if(areItemStacksIdentical(stack, mvstack)) {
@ -430,16 +427,16 @@ public class Inventories
for(int i=0; i<size; ++i) { for(int i=0; i<size; ++i) {
final int sno = reverse ? (size-1-i) : (i); final int sno = reverse ? (size-1-i) : (i);
if((empties[sno]) || (!matches[sno])) continue; if((empties[sno]) || (!matches[sno])) continue;
final ItemStack stack = getStackInSlot(sno); final ItemStack stack = getItem(sno);
int nmax = Math.min(limit_left, stack.getMaxStackSize() - stack.getCount()); int nmax = Math.min(limit_left, stack.getMaxStackSize() - stack.getCount());
if(mvstack.getCount() <= nmax) { if(mvstack.getCount() <= nmax) {
stack.setCount(stack.getCount()+mvstack.getCount()); stack.setCount(stack.getCount()+mvstack.getCount());
setInventorySlotContents(sno, stack); setItem(sno, stack);
return ItemStack.EMPTY; return ItemStack.EMPTY;
} else { } else {
stack.grow(nmax); stack.grow(nmax);
mvstack.shrink(nmax); mvstack.shrink(nmax);
setInventorySlotContents(sno, stack); setItem(sno, stack);
limit_left -= nmax; limit_left -= nmax;
} }
} }
@ -461,12 +458,12 @@ public class Inventories
} }
for(i=insert_start;i < insert_end; ++i) { for(i=insert_start;i < insert_end; ++i) {
final int sno = reverse ? (size-1-i) : (i); final int sno = reverse ? (size-1-i) : (i);
if((!empties[sno]) || (!isItemValidForSlot(sno, mvstack))) continue; if((!empties[sno]) || (!canPlaceItem(sno, mvstack))) continue;
int nmax = Math.min(limit_left, mvstack.getCount()); int nmax = Math.min(limit_left, mvstack.getCount());
ItemStack moved = mvstack.copy(); ItemStack moved = mvstack.copy();
moved.setCount(nmax); moved.setCount(nmax);
mvstack.shrink(nmax); mvstack.shrink(nmax);
setInventorySlotContents(sno, moved); setItem(sno, moved);
return checked(mvstack); return checked(mvstack);
} }
} }
@ -476,12 +473,12 @@ public class Inventories
final int sno = reverse ? (size-1-i) : (i); final int sno = reverse ? (size-1-i) : (i);
if(!matches[sno]) continue; if(!matches[sno]) continue;
int ii = (empties[sno-1]) ? (sno-1) : (empties[sno+1] ? (sno+1) : -1); int ii = (empties[sno-1]) ? (sno-1) : (empties[sno+1] ? (sno+1) : -1);
if((ii >= 0) && (isItemValidForSlot(ii, mvstack))) { if((ii >= 0) && (canPlaceItem(ii, mvstack))) {
int nmax = Math.min(limit_left, mvstack.getCount()); int nmax = Math.min(limit_left, mvstack.getCount());
ItemStack moved = mvstack.copy(); ItemStack moved = mvstack.copy();
moved.setCount(nmax); moved.setCount(nmax);
mvstack.shrink(nmax); mvstack.shrink(nmax);
setInventorySlotContents(ii, moved); setItem(ii, moved);
return checked(mvstack); return checked(mvstack);
} }
} }
@ -490,12 +487,12 @@ public class Inventories
// third iteration: use any empty slots // third iteration: use any empty slots
for(int i=0; i<size; ++i) { for(int i=0; i<size; ++i) {
final int sno = reverse ? (size-1-i) : (i); final int sno = reverse ? (size-1-i) : (i);
if((!empties[sno]) || (!isItemValidForSlot(sno, mvstack))) continue; if((!empties[sno]) || (!canPlaceItem(sno, mvstack))) continue;
int nmax = Math.min(limit_left, mvstack.getCount()); int nmax = Math.min(limit_left, mvstack.getCount());
ItemStack placed = mvstack.copy(); ItemStack placed = mvstack.copy();
placed.setCount(nmax); placed.setCount(nmax);
mvstack.shrink(nmax); mvstack.shrink(nmax);
setInventorySlotContents(sno, placed); setItem(sno, placed);
return checked(mvstack); return checked(mvstack);
} }
return checked(mvstack); return checked(mvstack);
@ -513,7 +510,7 @@ public class Inventories
if(request_stack.isEmpty()) return ItemStack.EMPTY; if(request_stack.isEmpty()) return ItemStack.EMPTY;
List<ItemStack> matches = new ArrayList<>(); List<ItemStack> matches = new ArrayList<>();
for(int i=0; i<size; ++i) { for(int i=0; i<size; ++i) {
final ItemStack stack = getStackInSlot(i); final ItemStack stack = getItem(i);
if((!stack.isEmpty()) && (areItemStacksIdentical(stack, request_stack))) { if((!stack.isEmpty()) && (areItemStacksIdentical(stack, request_stack))) {
if(stack.hasTag()) { if(stack.hasTag()) {
final CompoundNBT nbt = stack.getTag(); final CompoundNBT nbt = stack.getTag();
@ -543,15 +540,15 @@ public class Inventories
*/ */
public boolean move(int index, final InventoryRange target_range, boolean all_identical_stacks, boolean only_fillup, boolean reverse, boolean force_group_stacks) public boolean move(int index, final InventoryRange target_range, boolean all_identical_stacks, boolean only_fillup, boolean reverse, boolean force_group_stacks)
{ {
final ItemStack source_stack = getStackInSlot(index); final ItemStack source_stack = getItem(index);
if(source_stack.isEmpty()) return false; if(source_stack.isEmpty()) return false;
if(!all_identical_stacks) { if(!all_identical_stacks) {
ItemStack remaining = target_range.insert(source_stack, only_fillup, 0, reverse, force_group_stacks); ItemStack remaining = target_range.insert(source_stack, only_fillup, 0, reverse, force_group_stacks);
setInventorySlotContents(index, remaining); setItem(index, remaining);
return (remaining.getCount() != source_stack.getCount()); return (remaining.getCount() != source_stack.getCount());
} else { } else {
ItemStack remaining = source_stack.copy(); ItemStack remaining = source_stack.copy();
setInventorySlotContents(index, ItemStack.EMPTY); setItem(index, ItemStack.EMPTY);
final ItemStack ref_stack = remaining.copy(); final ItemStack ref_stack = remaining.copy();
ref_stack.setCount(ref_stack.getMaxStackSize()); ref_stack.setCount(ref_stack.getMaxStackSize());
for(int i=size; (i>0) && (!remaining.isEmpty()); --i) { for(int i=size; (i>0) && (!remaining.isEmpty()); --i) {
@ -560,7 +557,7 @@ public class Inventories
remaining = this.extract(ref_stack); remaining = this.extract(ref_stack);
} }
if(!remaining.isEmpty()) { if(!remaining.isEmpty()) {
setInventorySlotContents(index, remaining); // put back setItem(index, remaining); // put back
} }
return (remaining.getCount() != source_stack.getCount()); return (remaining.getCount() != source_stack.getCount());
} }
@ -608,7 +605,7 @@ public class Inventories
public ItemStack next() public ItemStack next()
{ {
if(index >= parent_.size) throw new NoSuchElementException(); if(index >= parent_.size) throw new NoSuchElementException();
return parent_.getStackInSlot(index++); return parent_.getItem(index++);
} }
} }
} }
@ -689,7 +686,7 @@ public class Inventories
// IInventory ------------------------------------------------------------------------------ // IInventory ------------------------------------------------------------------------------
@Override @Override
public int getSizeInventory() public int getContainerSize()
{ return size_; } { return size_; }
@Override @Override
@ -697,19 +694,19 @@ public class Inventories
{ for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; } { for(ItemStack stack: stacks_) { if(!stack.isEmpty()) return false; } return true; }
@Override @Override
public ItemStack getStackInSlot(int index) public ItemStack getItem(int index)
{ return (index < size_) ? stacks_.get(index) : ItemStack.EMPTY; } { return (index < size_) ? stacks_.get(index) : ItemStack.EMPTY; }
@Override @Override
public ItemStack decrStackSize(int index, int count) public ItemStack removeItem(int index, int count)
{ return ItemStackHelper.getAndSplit(stacks_, index, count); } { return ItemStackHelper.removeItem(stacks_, index, count); }
@Override @Override
public ItemStack removeStackFromSlot(int index) public ItemStack removeItemNoUpdate(int index)
{ return ItemStackHelper.getAndRemove(stacks_, index); } { return ItemStackHelper.takeItem(stacks_, index); }
@Override @Override
public void setInventorySlotContents(int index, ItemStack stack) public void setItem(int index, ItemStack stack)
{ {
stacks_.set(index, stack); stacks_.set(index, stack);
if((stack.getCount() != stacks_.get(index).getCount()) || !areItemStacksDifferent(stacks_.get(index),stack)) { if((stack.getCount() != stacks_.get(index).getCount()) || !areItemStacksDifferent(stacks_.get(index),stack)) {
@ -718,32 +715,32 @@ public class Inventories
} }
@Override @Override
public int getInventoryStackLimit() public int getMaxStackSize()
{ return stack_limit_; } { return stack_limit_; }
@Override @Override
public void markDirty() public void setChanged()
{ te_.markDirty(); } { te_.setChanged(); }
@Override @Override
public boolean isUsableByPlayer(PlayerEntity player) public boolean stillValid(PlayerEntity player)
{ return ((te_.getWorld().getTileEntity(te_.getPos()) == te_)) && (te_.getPos().distanceSq(player.getPosition()) < 64); } { return ((te_.getLevel().getBlockEntity(te_.getBlockPos()) == te_)) && (te_.getBlockPos().distSqr(player.blockPosition()) < 64); }
@Override @Override
public void openInventory(PlayerEntity player) public void startOpen(PlayerEntity player)
{ open_action_.accept(player); } { open_action_.accept(player); }
@Override @Override
public void closeInventory(PlayerEntity player) public void stopOpen(PlayerEntity player)
{ markDirty(); close_action_.accept(player); } { setChanged(); close_action_.accept(player); }
@Override @Override
public boolean isItemValidForSlot(int index, ItemStack stack) public boolean canPlaceItem(int index, ItemStack stack)
{ return validator_.test(index, stack); } { return validator_.test(index, stack); }
@Override @Override
public void clear() public void clearContent()
{ stacks_.clear(); markDirty(); } { stacks_.clear(); setChanged(); }
} }
@ -755,9 +752,9 @@ public class Inventories
public static void setItemInPlayerHand(PlayerEntity player, Hand hand, ItemStack stack) { public static void setItemInPlayerHand(PlayerEntity player, Hand hand, ItemStack stack) {
if(stack.isEmpty()) stack = ItemStack.EMPTY; if(stack.isEmpty()) stack = ItemStack.EMPTY;
if(hand == Hand.MAIN_HAND) { if(hand == Hand.MAIN_HAND) {
player.inventory.mainInventory.set(player.inventory.currentItem, stack); player.inventory.items.set(player.inventory.selected, stack);
} else { } else {
player.inventory.offHandInventory.set(0, stack); player.inventory.offhand.set(0, stack);
} }
} }
@ -765,8 +762,8 @@ public class Inventories
public static IInventory readNbtStacks(CompoundNBT nbt, String key, IInventory target) public static IInventory readNbtStacks(CompoundNBT nbt, String key, IInventory target)
{ {
NonNullList<ItemStack> stacks = Inventories.readNbtStacks(nbt, key, target.getSizeInventory()); NonNullList<ItemStack> stacks = Inventories.readNbtStacks(nbt, key, target.getContainerSize());
for(int i=0; i<stacks.size(); ++i) target.setInventorySlotContents(i, stacks.get(i)); for(int i=0; i<stacks.size(); ++i) target.setItem(i, stacks.get(i));
return target; return target;
} }

View file

@ -75,13 +75,13 @@ public class Networking
{ this.nbt = nbt; this.pos = pos; } { this.nbt = nbt; this.pos = pos; }
public PacketTileNotifyClientToServer(TileEntity te, CompoundNBT nbt) public PacketTileNotifyClientToServer(TileEntity te, CompoundNBT nbt)
{ this.nbt = nbt; pos = te.getPos(); } { this.nbt = nbt; pos = te.getBlockPos(); }
public static PacketTileNotifyClientToServer parse(final PacketBuffer buf) public static PacketTileNotifyClientToServer parse(final PacketBuffer buf)
{ return new PacketTileNotifyClientToServer(buf.readBlockPos(), buf.readCompoundTag()); } { return new PacketTileNotifyClientToServer(buf.readBlockPos(), buf.readNbt()); }
public static void compose(final PacketTileNotifyClientToServer pkt, final PacketBuffer buf) public static void compose(final PacketTileNotifyClientToServer pkt, final PacketBuffer buf)
{ buf.writeBlockPos(pkt.pos); buf.writeCompoundTag(pkt.nbt); } { buf.writeBlockPos(pkt.pos); buf.writeNbt(pkt.nbt); }
public static class Handler public static class Handler
{ {
@ -89,9 +89,9 @@ public class Networking
{ {
ctx.get().enqueueWork(() -> { ctx.get().enqueueWork(() -> {
PlayerEntity player = ctx.get().getSender(); PlayerEntity player = ctx.get().getSender();
World world = player.world; World world = player.level;
if(world == null) return; if(world == null) return;
final TileEntity te = world.getTileEntity(pkt.pos); final TileEntity te = world.getBlockEntity(pkt.pos);
if(!(te instanceof IPacketTileNotifyReceiver)) return; if(!(te instanceof IPacketTileNotifyReceiver)) return;
((IPacketTileNotifyReceiver)te).onClientPacketReceived(ctx.get().getSender(), pkt.nbt); ((IPacketTileNotifyReceiver)te).onClientPacketReceived(ctx.get().getSender(), pkt.nbt);
}); });
@ -108,13 +108,13 @@ public class Networking
public static void sendToPlayer(PlayerEntity player, TileEntity te, CompoundNBT nbt) public static void sendToPlayer(PlayerEntity player, TileEntity te, CompoundNBT nbt)
{ {
if((!(player instanceof ServerPlayerEntity)) || (player instanceof FakePlayer) || (te==null) || (nbt==null)) return; if((!(player instanceof ServerPlayerEntity)) || (player instanceof FakePlayer) || (te==null) || (nbt==null)) return;
DEFAULT_CHANNEL.sendTo(new PacketTileNotifyServerToClient(te, nbt), ((ServerPlayerEntity)player).connection.netManager, NetworkDirection.PLAY_TO_CLIENT); DEFAULT_CHANNEL.sendTo(new PacketTileNotifyServerToClient(te, nbt), ((ServerPlayerEntity)player).connection.connection, NetworkDirection.PLAY_TO_CLIENT);
} }
public static void sendToPlayers(TileEntity te, CompoundNBT nbt) public static void sendToPlayers(TileEntity te, CompoundNBT nbt)
{ {
if(te==null || te.getWorld().isRemote()) return; if(te==null || te.getLevel().isClientSide()) return;
for(PlayerEntity player: te.getWorld().getPlayers()) sendToPlayer(player, te, nbt); for(PlayerEntity player: te.getLevel().players()) sendToPlayer(player, te, nbt);
} }
public PacketTileNotifyServerToClient() public PacketTileNotifyServerToClient()
@ -124,13 +124,13 @@ public class Networking
{ this.nbt=nbt; this.pos=pos; } { this.nbt=nbt; this.pos=pos; }
public PacketTileNotifyServerToClient(TileEntity te, CompoundNBT nbt) public PacketTileNotifyServerToClient(TileEntity te, CompoundNBT nbt)
{ this.nbt=nbt; pos=te.getPos(); } { this.nbt=nbt; pos=te.getBlockPos(); }
public static PacketTileNotifyServerToClient parse(final PacketBuffer buf) public static PacketTileNotifyServerToClient parse(final PacketBuffer buf)
{ return new PacketTileNotifyServerToClient(buf.readBlockPos(), buf.readCompoundTag()); } { return new PacketTileNotifyServerToClient(buf.readBlockPos(), buf.readNbt()); }
public static void compose(final PacketTileNotifyServerToClient pkt, final PacketBuffer buf) public static void compose(final PacketTileNotifyServerToClient pkt, final PacketBuffer buf)
{ buf.writeBlockPos(pkt.pos); buf.writeCompoundTag(pkt.nbt); } { buf.writeBlockPos(pkt.pos); buf.writeNbt(pkt.nbt); }
public static class Handler public static class Handler
{ {
@ -139,7 +139,7 @@ public class Networking
ctx.get().enqueueWork(() -> { ctx.get().enqueueWork(() -> {
World world = SidedProxy.getWorldClientSide(); World world = SidedProxy.getWorldClientSide();
if(world == null) return; if(world == null) return;
final TileEntity te = world.getTileEntity(pkt.pos); final TileEntity te = world.getBlockEntity(pkt.pos);
if(!(te instanceof IPacketTileNotifyReceiver)) return; if(!(te instanceof IPacketTileNotifyReceiver)) return;
((IPacketTileNotifyReceiver)te).onServerPacketReceived(pkt.nbt); ((IPacketTileNotifyReceiver)te).onServerPacketReceived(pkt.nbt);
}); });
@ -167,7 +167,7 @@ public class Networking
{ if(nbt!=null) DEFAULT_CHANNEL.sendToServer(new PacketContainerSyncClientToServer(windowId, nbt)); } { if(nbt!=null) DEFAULT_CHANNEL.sendToServer(new PacketContainerSyncClientToServer(windowId, nbt)); }
public static void sendToServer(Container container, CompoundNBT nbt) public static void sendToServer(Container container, CompoundNBT nbt)
{ if(nbt!=null) DEFAULT_CHANNEL.sendToServer(new PacketContainerSyncClientToServer(container.windowId, nbt)); } { if(nbt!=null) DEFAULT_CHANNEL.sendToServer(new PacketContainerSyncClientToServer(container.containerId, nbt)); }
public PacketContainerSyncClientToServer() public PacketContainerSyncClientToServer()
{} {}
@ -176,10 +176,10 @@ public class Networking
{ this.nbt = nbt; this.id = id; } { this.nbt = nbt; this.id = id; }
public static PacketContainerSyncClientToServer parse(final PacketBuffer buf) public static PacketContainerSyncClientToServer parse(final PacketBuffer buf)
{ return new PacketContainerSyncClientToServer(buf.readInt(), buf.readCompoundTag()); } { return new PacketContainerSyncClientToServer(buf.readInt(), buf.readNbt()); }
public static void compose(final PacketContainerSyncClientToServer pkt, final PacketBuffer buf) public static void compose(final PacketContainerSyncClientToServer pkt, final PacketBuffer buf)
{ buf.writeInt(pkt.id); buf.writeCompoundTag(pkt.nbt); } { buf.writeInt(pkt.id); buf.writeNbt(pkt.nbt); }
public static class Handler public static class Handler
{ {
@ -187,9 +187,9 @@ public class Networking
{ {
ctx.get().enqueueWork(() -> { ctx.get().enqueueWork(() -> {
PlayerEntity player = ctx.get().getSender(); PlayerEntity player = ctx.get().getSender();
if(!(player.openContainer instanceof INetworkSynchronisableContainer)) return; if(!(player.containerMenu instanceof INetworkSynchronisableContainer)) return;
if(player.openContainer.windowId != pkt.id) return; if(player.containerMenu.containerId != pkt.id) return;
((INetworkSynchronisableContainer)player.openContainer).onClientPacketReceived(pkt.id, player,pkt.nbt); ((INetworkSynchronisableContainer)player.containerMenu).onClientPacketReceived(pkt.id, player,pkt.nbt);
}); });
ctx.get().setPacketHandled(true); ctx.get().setPacketHandled(true);
} }
@ -204,21 +204,21 @@ public class Networking
public static void sendToPlayer(PlayerEntity player, int windowId, CompoundNBT nbt) public static void sendToPlayer(PlayerEntity player, int windowId, CompoundNBT nbt)
{ {
if((!(player instanceof ServerPlayerEntity)) || (player instanceof FakePlayer) || (nbt==null)) return; if((!(player instanceof ServerPlayerEntity)) || (player instanceof FakePlayer) || (nbt==null)) return;
DEFAULT_CHANNEL.sendTo(new PacketContainerSyncServerToClient(windowId, nbt), ((ServerPlayerEntity)player).connection.netManager, NetworkDirection.PLAY_TO_CLIENT); DEFAULT_CHANNEL.sendTo(new PacketContainerSyncServerToClient(windowId, nbt), ((ServerPlayerEntity)player).connection.connection, NetworkDirection.PLAY_TO_CLIENT);
} }
public static void sendToPlayer(PlayerEntity player, Container container, CompoundNBT nbt) public static void sendToPlayer(PlayerEntity player, Container container, CompoundNBT nbt)
{ {
if((!(player instanceof ServerPlayerEntity)) || (player instanceof FakePlayer) || (nbt==null)) return; if((!(player instanceof ServerPlayerEntity)) || (player instanceof FakePlayer) || (nbt==null)) return;
DEFAULT_CHANNEL.sendTo(new PacketContainerSyncServerToClient(container.windowId, nbt), ((ServerPlayerEntity)player).connection.netManager, NetworkDirection.PLAY_TO_CLIENT); DEFAULT_CHANNEL.sendTo(new PacketContainerSyncServerToClient(container.containerId, nbt), ((ServerPlayerEntity)player).connection.connection, NetworkDirection.PLAY_TO_CLIENT);
} }
public static <C extends Container & INetworkSynchronisableContainer> public static <C extends Container & INetworkSynchronisableContainer>
void sendToListeners(World world, C container, CompoundNBT nbt) void sendToListeners(World world, C container, CompoundNBT nbt)
{ {
for(PlayerEntity player: world.getPlayers()) { for(PlayerEntity player: world.players()) {
if(player.openContainer.windowId != container.windowId) continue; if(player.containerMenu.containerId != container.containerId) continue;
sendToPlayer(player, container.windowId, nbt); sendToPlayer(player, container.containerId, nbt);
} }
} }
@ -229,10 +229,10 @@ public class Networking
{ this.nbt=nbt; this.id=id; } { this.nbt=nbt; this.id=id; }
public static PacketContainerSyncServerToClient parse(final PacketBuffer buf) public static PacketContainerSyncServerToClient parse(final PacketBuffer buf)
{ return new PacketContainerSyncServerToClient(buf.readInt(), buf.readCompoundTag()); } { return new PacketContainerSyncServerToClient(buf.readInt(), buf.readNbt()); }
public static void compose(final PacketContainerSyncServerToClient pkt, final PacketBuffer buf) public static void compose(final PacketContainerSyncServerToClient pkt, final PacketBuffer buf)
{ buf.writeInt(pkt.id); buf.writeCompoundTag(pkt.nbt); } { buf.writeInt(pkt.id); buf.writeNbt(pkt.nbt); }
public static class Handler public static class Handler
{ {
@ -240,9 +240,9 @@ public class Networking
{ {
ctx.get().enqueueWork(() -> { ctx.get().enqueueWork(() -> {
PlayerEntity player = SidedProxy.getPlayerClientSide(); PlayerEntity player = SidedProxy.getPlayerClientSide();
if(!(player.openContainer instanceof INetworkSynchronisableContainer)) return; if(!(player.containerMenu instanceof INetworkSynchronisableContainer)) return;
if(player.openContainer.windowId != pkt.id) return; if(player.containerMenu.containerId != pkt.id) return;
((INetworkSynchronisableContainer)player.openContainer).onServerPacketReceived(pkt.id,pkt.nbt); ((INetworkSynchronisableContainer)player.containerMenu).onServerPacketReceived(pkt.id,pkt.nbt);
}); });
ctx.get().setPacketHandled(true); ctx.get().setPacketHandled(true);
} }
@ -269,19 +269,19 @@ public class Networking
public static void sendToPlayer(PlayerEntity player, ITextComponent message, int delay) public static void sendToPlayer(PlayerEntity player, ITextComponent message, int delay)
{ {
if((!(player instanceof ServerPlayerEntity)) || (player instanceof FakePlayer)) return; if((!(player instanceof ServerPlayerEntity)) || (player instanceof FakePlayer)) return;
DEFAULT_CHANNEL.sendTo(new OverlayTextMessage(message, delay), ((ServerPlayerEntity)player).connection.netManager, NetworkDirection.PLAY_TO_CLIENT); DEFAULT_CHANNEL.sendTo(new OverlayTextMessage(message, delay), ((ServerPlayerEntity)player).connection.connection, NetworkDirection.PLAY_TO_CLIENT);
} }
public OverlayTextMessage() public OverlayTextMessage()
{ data_ = new TranslationTextComponent("[unset]"); } { data_ = new TranslationTextComponent("[unset]"); }
public OverlayTextMessage(final ITextComponent tct, int delay) public OverlayTextMessage(final ITextComponent tct, int delay)
{ data_ = (ITextComponent)tct.deepCopy(); delay_ = delay; } { data_ = (ITextComponent)tct.copy(); delay_ = delay; }
public static OverlayTextMessage parse(final PacketBuffer buf) public static OverlayTextMessage parse(final PacketBuffer buf)
{ {
try { try {
return new OverlayTextMessage((ITextComponent)buf.readTextComponent(), DISPLAY_TIME_MS); return new OverlayTextMessage((ITextComponent)buf.readComponent(), DISPLAY_TIME_MS);
} catch(Throwable e) { } catch(Throwable e) {
return new OverlayTextMessage(new TranslationTextComponent("[incorrect translation]"), DISPLAY_TIME_MS); return new OverlayTextMessage(new TranslationTextComponent("[incorrect translation]"), DISPLAY_TIME_MS);
} }
@ -290,7 +290,7 @@ public class Networking
public static void compose(final OverlayTextMessage pkt, final PacketBuffer buf) public static void compose(final OverlayTextMessage pkt, final PacketBuffer buf)
{ {
try { try {
buf.writeTextComponent(pkt.data()); buf.writeComponent(pkt.data());
} catch(Throwable e) { } catch(Throwable e) {
Auxiliaries.logger().error("OverlayTextMessage.toBytes() failed: " + e.toString()); Auxiliaries.logger().error("OverlayTextMessage.toBytes() failed: " + e.toString());
} }

View file

@ -97,7 +97,7 @@ public class OptionalRecipeCondition implements ICondition
if(without_recipes) return false; if(without_recipes) return false;
if((experimental) && (!with_experimental)) return false; if((experimental) && (!with_experimental)) return false;
final IForgeRegistry<Item> item_registry = ForgeRegistries.ITEMS; final IForgeRegistry<Item> item_registry = ForgeRegistries.ITEMS;
final Map<ResourceLocation, ITag<Item>> item_tags = TagCollectionManager.getManager().getItemTags().getIDTagMap(); final Map<ResourceLocation, ITag<Item>> item_tags = TagCollectionManager.getInstance().getItems().getAllTags();
if(result != null) { if(result != null) {
boolean item_registered = item_registry.containsKey(result); boolean item_registered = item_registry.containsKey(result);
if(!item_registered) return false; // required result not registered if(!item_registered) return false; // required result not registered
@ -112,7 +112,7 @@ public class OptionalRecipeCondition implements ICondition
if(!all_required_tags.isEmpty()) { if(!all_required_tags.isEmpty()) {
for(ResourceLocation rl:all_required_tags) { for(ResourceLocation rl:all_required_tags) {
if(!item_tags.containsKey(rl)) return false; if(!item_tags.containsKey(rl)) return false;
if(item_tags.get(rl).getAllElements().isEmpty()) return false; if(item_tags.get(rl).getValues().isEmpty()) return false;
} }
} }
if(!any_missing.isEmpty()) { if(!any_missing.isEmpty()) {
@ -124,7 +124,7 @@ public class OptionalRecipeCondition implements ICondition
if(!any_missing_tags.isEmpty()) { if(!any_missing_tags.isEmpty()) {
for(ResourceLocation rl:any_missing_tags) { for(ResourceLocation rl:any_missing_tags) {
if(!item_tags.containsKey(rl)) return true; if(!item_tags.containsKey(rl)) return true;
if(item_tags.get(rl).getAllElements().isEmpty()) return true; if(item_tags.get(rl).getValues().isEmpty()) return true;
} }
return false; return false;
} }
@ -173,7 +173,7 @@ public class OptionalRecipeCondition implements ICondition
} }
} }
if(json.has("required")) { if(json.has("required")) {
for(JsonElement e:JSONUtils.getJsonArray(json, "required")) { for(JsonElement e:JSONUtils.getAsJsonArray(json, "required")) {
String s = e.getAsString(); String s = e.getAsString();
if(s.startsWith("#")) { if(s.startsWith("#")) {
required_tags.add(new ResourceLocation(s.substring(1))); required_tags.add(new ResourceLocation(s.substring(1)));
@ -183,7 +183,7 @@ public class OptionalRecipeCondition implements ICondition
} }
} }
if(json.has("missing")) { if(json.has("missing")) {
for(JsonElement e:JSONUtils.getJsonArray(json, "missing")) { for(JsonElement e:JSONUtils.getAsJsonArray(json, "missing")) {
String s = e.getAsString(); String s = e.getAsString();
if(s.startsWith("#")) { if(s.startsWith("#")) {
missing_tags.add(new ResourceLocation(s.substring(1))); missing_tags.add(new ResourceLocation(s.substring(1)));

View file

@ -77,7 +77,7 @@ public class Overlay
{ deadline_ = 0; text_ = EMPTY_TEXT; } { deadline_ = 0; text_ = EMPTY_TEXT; }
public static synchronized void show(ITextComponent s, int displayTimeoutMs) public static synchronized void show(ITextComponent s, int displayTimeoutMs)
{ text_ = (s==null)?(EMPTY_TEXT):(s.deepCopy()); deadline_ = System.currentTimeMillis() + displayTimeoutMs; } { text_ = (s==null)?(EMPTY_TEXT):(s.copy()); deadline_ = System.currentTimeMillis() + displayTimeoutMs; }
public static synchronized void show(String s, int displayTimeoutMs) public static synchronized void show(String s, int displayTimeoutMs)
{ text_ = ((s==null)||(s.isEmpty()))?(EMPTY_TEXT):(new StringTextComponent(s)); deadline_ = System.currentTimeMillis() + displayTimeoutMs; } { text_ = ((s==null)||(s.isEmpty()))?(EMPTY_TEXT):(new StringTextComponent(s)); deadline_ = System.currentTimeMillis() + displayTimeoutMs; }
@ -94,14 +94,14 @@ public class Overlay
String txt = text().getString(); String txt = text().getString();
if(txt.isEmpty()) return; if(txt.isEmpty()) return;
MatrixStack mxs = event.getMatrixStack(); MatrixStack mxs = event.getMatrixStack();
final MainWindow win = mc.getMainWindow(); final MainWindow win = mc.getWindow();
final FontRenderer fr = mc.fontRenderer; final FontRenderer fr = mc.font;
final boolean was_unicode = fr.getBidiFlag(); final boolean was_unicode = fr.isBidirectional();
try { try {
final int cx = win.getScaledWidth() / 2; final int cx = win.getGuiScaledWidth() / 2;
final int cy = (int)(win.getScaledHeight() * overlay_y_); final int cy = (int)(win.getGuiScaledHeight() * overlay_y_);
final int w = fr.getStringWidth(txt); final int w = fr.width(txt);
final int h = fr.FONT_HEIGHT; final int h = fr.lineHeight;
fillGradient(mxs, cx-(w/2)-3, cy-2, cx+(w/2)+2, cy+h+2, 0xaa333333, 0xaa444444); fillGradient(mxs, cx-(w/2)-3, cy-2, cx+(w/2)+2, cy+h+2, 0xaa333333, 0xaa444444);
hLine(mxs, cx-(w/2)-3, cx+(w/2)+2, cy-2, 0xaa333333); hLine(mxs, cx-(w/2)-3, cx+(w/2)+2, cy-2, 0xaa333333);
hLine(mxs, cx-(w/2)-3, cx+(w/2)+2, cy+h+2, 0xaa333333); hLine(mxs, cx-(w/2)-3, cx+(w/2)+2, cy+h+2, 0xaa333333);

View file

@ -24,7 +24,7 @@ public class RfEnergy
{ {
public static int feed(World world, BlockPos pos, @Nullable Direction side, int rf_energy) public static int feed(World world, BlockPos pos, @Nullable Direction side, int rf_energy)
{ {
final TileEntity te = world.getTileEntity(pos); final TileEntity te = world.getBlockEntity(pos);
if(te == null) return 0; if(te == null) return 0;
final IEnergyStorage es = te.getCapability(CapabilityEnergy.ENERGY, side).orElse(null); final IEnergyStorage es = te.getCapability(CapabilityEnergy.ENERGY, side).orElse(null);
if(es == null) return 0; if(es == null) return 0;

View file

@ -54,7 +54,7 @@ public class SidedProxy
private static final class ClientProxy implements ISidedProxy private static final class ClientProxy implements ISidedProxy
{ {
public @Nullable PlayerEntity getPlayerClientSide() { return Minecraft.getInstance().player; } public @Nullable PlayerEntity getPlayerClientSide() { return Minecraft.getInstance().player; }
public @Nullable World getWorldClientSide() { return Minecraft.getInstance().world; } public @Nullable World getWorldClientSide() { return Minecraft.getInstance().level; }
public @Nullable Minecraft mc() { return Minecraft.getInstance(); } public @Nullable Minecraft mc() { return Minecraft.getInstance(); }
public Optional<Boolean> isCtrlDown() { return Optional.of(Auxiliaries.isCtrlDown()); } public Optional<Boolean> isCtrlDown() { return Optional.of(Auxiliaries.isCtrlDown()); }
public Optional<Boolean> isShiftDown() { return Optional.of(Auxiliaries.isShiftDown()); } public Optional<Boolean> isShiftDown() { return Optional.of(Auxiliaries.isShiftDown()); }