78 lines
2.5 KiB
Java
78 lines
2.5 KiB
Java
package com.thebrokenrail.energonrelics.api.block;
|
|
|
|
import net.minecraft.block.BlockEntityProvider;
|
|
import net.minecraft.block.BlockState;
|
|
import net.minecraft.block.entity.BlockEntity;
|
|
import net.minecraft.block.entity.BlockEntityType;
|
|
import net.minecraft.inventory.Inventory;
|
|
import net.minecraft.screen.ScreenHandler;
|
|
import net.minecraft.util.Identifier;
|
|
import net.minecraft.util.ItemScatterer;
|
|
import net.minecraft.util.math.BlockPos;
|
|
import net.minecraft.util.registry.Registry;
|
|
import net.minecraft.world.BlockView;
|
|
import net.minecraft.world.World;
|
|
import org.jetbrains.annotations.ApiStatus;
|
|
|
|
import java.util.function.Function;
|
|
|
|
/**
|
|
* Simple Block With Entity
|
|
*/
|
|
@SuppressWarnings("deprecation")
|
|
public abstract class SimpleBlockWithEntity extends SimpleBlock implements BlockEntityProvider {
|
|
protected BlockEntityType<BlockEntity> type;
|
|
|
|
public SimpleBlockWithEntity(Settings settings) {
|
|
super(settings);
|
|
}
|
|
|
|
@Override
|
|
public void register(Identifier id) {
|
|
super.register(id);
|
|
type = Registry.register(Registry.BLOCK_ENTITY_TYPE, id, BlockEntityType.Builder.create(() -> getFactory().apply(type), this).build(null));
|
|
}
|
|
|
|
/**
|
|
* Factory To Create Block Entity
|
|
* @return Block Entity Factory
|
|
*/
|
|
protected abstract Function<BlockEntityType<BlockEntity>, BlockEntity> getFactory();
|
|
|
|
@Override
|
|
public BlockEntity createBlockEntity(BlockView world) {
|
|
return getFactory().apply(type);
|
|
}
|
|
|
|
/**
|
|
* Does This Block's Block Entity Have An Inventory
|
|
* @return Has Inventory
|
|
*/
|
|
@ApiStatus.OverrideOnly
|
|
protected boolean hasInventory() {
|
|
return false;
|
|
}
|
|
|
|
@Override
|
|
public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) {
|
|
if (state.getBlock() != newState.getBlock() && hasInventory()) {
|
|
BlockEntity blockEntity = world.getBlockEntity(pos);
|
|
if (blockEntity instanceof Inventory) {
|
|
ItemScatterer.spawn(world, pos, (Inventory) blockEntity);
|
|
world.updateComparators(pos, this);
|
|
}
|
|
}
|
|
super.onStateReplaced(state, world, pos, newState, moved);
|
|
}
|
|
|
|
@Override
|
|
public boolean hasComparatorOutput(BlockState state) {
|
|
return hasInventory();
|
|
}
|
|
|
|
@Override
|
|
public int getComparatorOutput(BlockState state, World world, BlockPos pos) {
|
|
return hasInventory() ? ScreenHandler.calculateComparatorOutput(world.getBlockEntity(pos)) : 0;
|
|
}
|
|
}
|